context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Cryptography; using Internal.Cryptography.Pal; using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Globalization; using System.Runtime.Serialization; using System.Text; namespace System.Security.Cryptography.X509Certificates { [Serializable] public class X509Certificate : IDisposable, IDeserializationCallback, ISerializable { private volatile byte[] _lazyCertHash; private volatile string _lazyIssuer; private volatile string _lazySubject; private volatile byte[] _lazySerialNumber; private volatile string _lazyKeyAlgorithm; private volatile byte[] _lazyKeyAlgorithmParameters; private volatile byte[] _lazyPublicKey; private DateTime _lazyNotBefore = DateTime.MinValue; private DateTime _lazyNotAfter = DateTime.MinValue; public virtual void Reset() { _lazyCertHash = null; _lazyIssuer = null; _lazySubject = null; _lazySerialNumber = null; _lazyKeyAlgorithm = null; _lazyKeyAlgorithmParameters = null; _lazyPublicKey = null; _lazyNotBefore = DateTime.MinValue; _lazyNotAfter = DateTime.MinValue; ICertificatePal pal = Pal; Pal = null; if (pal != null) pal.Dispose(); } public X509Certificate() { } public X509Certificate(byte[] data) { if (data != null && data.Length != 0) { // For compat reasons, this constructor treats passing a null or empty data set as the same as calling the nullary constructor. using (var safePasswordHandle = new SafePasswordHandle((string)null)) { Pal = CertificatePal.FromBlob(data, safePasswordHandle, X509KeyStorageFlags.DefaultKeySet); } } } public X509Certificate(byte[] rawData, string password) : this(rawData, password, X509KeyStorageFlags.DefaultKeySet) { } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, SecureString password) : this(rawData, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromBlob(rawData, safePasswordHandle, keyStorageFlags); } } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromBlob(rawData, safePasswordHandle, keyStorageFlags); } } public X509Certificate(IntPtr handle) { Pal = CertificatePal.FromHandle(handle); } internal X509Certificate(ICertificatePal pal) { Debug.Assert(pal != null); Pal = pal; } public X509Certificate(string fileName) : this(fileName, (string)null, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password) : this(fileName, password, X509KeyStorageFlags.DefaultKeySet) { } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, SecureString password) : this(fileName, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromFile(fileName, safePasswordHandle, keyStorageFlags); } } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) : this() { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromFile(fileName, safePasswordHandle, keyStorageFlags); } } public X509Certificate(X509Certificate cert) { if (cert == null) throw new ArgumentNullException(nameof(cert)); if (cert.Pal != null) { Pal = CertificatePal.FromOtherCert(cert); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Public API has already shipped.")] public X509Certificate(SerializationInfo info, StreamingContext context) : this() { byte[] rawData = (byte[])info.GetValue("RawData", typeof(byte[])); if (rawData != null) { using (var safePasswordHandle = new SafePasswordHandle((string)null)) { Pal = CertificatePal.FromBlob(rawData, safePasswordHandle, X509KeyStorageFlags.DefaultKeySet); } } } public static X509Certificate CreateFromCertFile(string filename) { return new X509Certificate(filename); } public static X509Certificate CreateFromSignedFile(string filename) { return new X509Certificate(filename); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("RawData", Pal?.RawData); } void IDeserializationCallback.OnDeserialization(object sender) { } public IntPtr Handle { get { if (Pal == null) return IntPtr.Zero; else return Pal.Handle; } } public string Issuer { get { ThrowIfInvalid(); string issuer = _lazyIssuer; if (issuer == null) issuer = _lazyIssuer = Pal.Issuer; return issuer; } } public string Subject { get { ThrowIfInvalid(); string subject = _lazySubject; if (subject == null) subject = _lazySubject = Pal.Subject; return subject; } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Reset(); } } public override bool Equals(object obj) { X509Certificate other = obj as X509Certificate; if (other == null) return false; return Equals(other); } public virtual bool Equals(X509Certificate other) { if (other == null) return false; if (Pal == null) return other.Pal == null; if (!Issuer.Equals(other.Issuer)) return false; byte[] thisSerialNumber = GetRawSerialNumber(); byte[] otherSerialNumber = other.GetRawSerialNumber(); if (thisSerialNumber.Length != otherSerialNumber.Length) return false; for (int i = 0; i < thisSerialNumber.Length; i++) { if (thisSerialNumber[i] != otherSerialNumber[i]) return false; } return true; } public virtual byte[] Export(X509ContentType contentType) { return Export(contentType, (string)null); } public virtual byte[] Export(X509ContentType contentType, string password) { VerifyContentType(contentType); if (Pal == null) throw new CryptographicException(ErrorCode.E_POINTER); // Not the greatest error, but needed for backward compat. using (var safePasswordHandle = new SafePasswordHandle(password)) using (IExportPal storePal = StorePal.FromCertificate(Pal)) { return storePal.Export(contentType, safePasswordHandle); } } [System.CLSCompliantAttribute(false)] public virtual byte[] Export(X509ContentType contentType, SecureString password) { VerifyContentType(contentType); if (Pal == null) throw new CryptographicException(ErrorCode.E_POINTER); // Not the greatest error, but needed for backward compat. using (var safePasswordHandle = new SafePasswordHandle(password)) using (IExportPal storePal = StorePal.FromCertificate(Pal)) { return storePal.Export(contentType, safePasswordHandle); } } public virtual string GetRawCertDataString() { ThrowIfInvalid(); return GetRawCertData().ToHexStringUpper(); } public virtual byte[] GetCertHash() { ThrowIfInvalid(); return GetRawCertHash().CloneByteArray(); } public virtual string GetCertHashString() { ThrowIfInvalid(); return GetRawCertHash().ToHexStringUpper(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawCertHash() { return _lazyCertHash ?? (_lazyCertHash = Pal.Thumbprint); } public virtual string GetEffectiveDateString() { return GetNotBefore().ToString(); } public virtual string GetExpirationDateString() { return GetNotAfter().ToString(); } public virtual string GetFormat() { return "X509"; } public virtual string GetPublicKeyString() { return GetPublicKey().ToHexStringUpper(); } public virtual byte[] GetRawCertData() { ThrowIfInvalid(); return Pal.RawData.CloneByteArray(); } public override int GetHashCode() { if (Pal == null) return 0; byte[] thumbPrint = GetRawCertHash(); int value = 0; for (int i = 0; i < thumbPrint.Length && i < 4; ++i) { value = value << 8 | thumbPrint[i]; } return value; } public virtual string GetKeyAlgorithm() { ThrowIfInvalid(); string keyAlgorithm = _lazyKeyAlgorithm; if (keyAlgorithm == null) keyAlgorithm = _lazyKeyAlgorithm = Pal.KeyAlgorithm; return keyAlgorithm; } public virtual byte[] GetKeyAlgorithmParameters() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = _lazyKeyAlgorithmParameters; if (keyAlgorithmParameters == null) keyAlgorithmParameters = _lazyKeyAlgorithmParameters = Pal.KeyAlgorithmParameters; return keyAlgorithmParameters.CloneByteArray(); } public virtual string GetKeyAlgorithmParametersString() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = GetKeyAlgorithmParameters(); return keyAlgorithmParameters.ToHexStringUpper(); } public virtual byte[] GetPublicKey() { ThrowIfInvalid(); byte[] publicKey = _lazyPublicKey; if (publicKey == null) publicKey = _lazyPublicKey = Pal.PublicKeyValue; return publicKey.CloneByteArray(); } public virtual byte[] GetSerialNumber() { ThrowIfInvalid(); return GetRawSerialNumber().CloneByteArray(); } public virtual string GetSerialNumberString() { ThrowIfInvalid(); return GetRawSerialNumber().ToHexStringUpper(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawSerialNumber() { return _lazySerialNumber ?? (_lazySerialNumber = Pal.SerialNumber); } [Obsolete("This method has been deprecated. Please use the Subject property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetName() { return Subject; } [Obsolete("This method has been deprecated. Please use the Issuer property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetIssuerName() { return Issuer; } public override string ToString() { return ToString(fVerbose: false); } public virtual string ToString(bool fVerbose) { if (fVerbose == false || Pal == null) return GetType().ToString(); StringBuilder sb = new StringBuilder(); // Subject sb.AppendLine("[Subject]"); sb.Append(" "); sb.AppendLine(Subject); // Issuer sb.AppendLine(); sb.AppendLine("[Issuer]"); sb.Append(" "); sb.AppendLine(Issuer); // Serial Number sb.AppendLine(); sb.AppendLine("[Serial Number]"); sb.Append(" "); byte[] serialNumber = GetSerialNumber(); Array.Reverse(serialNumber); sb.Append(serialNumber.ToHexArrayUpper()); sb.AppendLine(); // NotBefore sb.AppendLine(); sb.AppendLine("[Not Before]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotBefore())); // NotAfter sb.AppendLine(); sb.AppendLine("[Not After]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotAfter())); // Thumbprint sb.AppendLine(); sb.AppendLine("[Thumbprint]"); sb.Append(" "); sb.Append(GetRawCertHash().ToHexArrayUpper()); sb.AppendLine(); return sb.ToString(); } public virtual void Import(byte[] rawData) { throw new PlatformNotSupportedException(); } public virtual void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(); } [System.CLSCompliantAttribute(false)] public virtual void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(); } public virtual void Import(string fileName) { throw new PlatformNotSupportedException(); } public virtual void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(); } [System.CLSCompliantAttribute(false)] public virtual void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(); } internal ICertificatePal Pal { get; private set; } internal DateTime GetNotAfter() { ThrowIfInvalid(); DateTime notAfter = _lazyNotAfter; if (notAfter == DateTime.MinValue) notAfter = _lazyNotAfter = Pal.NotAfter; return notAfter; } internal DateTime GetNotBefore() { ThrowIfInvalid(); DateTime notBefore = _lazyNotBefore; if (notBefore == DateTime.MinValue) notBefore = _lazyNotBefore = Pal.NotBefore; return notBefore; } internal void ThrowIfInvalid() { if (Pal == null) throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHandle, "m_safeCertContext")); // Keeping "m_safeCertContext" string for backward compat sake. } /// <summary> /// Convert a date to a string. /// /// Some cultures, specifically using the Um-AlQura calendar cannot convert dates far into /// the future into strings. If the expiration date of an X.509 certificate is beyond the range /// of one of these cases, we need to fall back to a calendar which can express the dates /// </summary> protected static string FormatDate(DateTime date) { CultureInfo culture = CultureInfo.CurrentCulture; if (!culture.DateTimeFormat.Calendar.IsValidDay(date.Year, date.Month, date.Day, 0)) { // The most common case of culture failing to work is in the Um-AlQuara calendar. In this case, // we can fall back to the Hijri calendar, otherwise fall back to the invariant culture. if (culture.DateTimeFormat.Calendar is UmAlQuraCalendar) { culture = culture.Clone() as CultureInfo; culture.DateTimeFormat.Calendar = new HijriCalendar(); } else { culture = CultureInfo.InvariantCulture; } } return date.ToString(culture); } internal static void ValidateKeyStorageFlags(X509KeyStorageFlags keyStorageFlags) { if ((keyStorageFlags & ~KeyStorageFlagsAll) != 0) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(keyStorageFlags)); const X509KeyStorageFlags EphemeralPersist = X509KeyStorageFlags.EphemeralKeySet | X509KeyStorageFlags.PersistKeySet; X509KeyStorageFlags persistenceFlags = keyStorageFlags & EphemeralPersist; if (persistenceFlags == EphemeralPersist) { throw new ArgumentException( SR.Format(SR.Cryptography_X509_InvalidFlagCombination, persistenceFlags), nameof(keyStorageFlags)); } } private void VerifyContentType(X509ContentType contentType) { if (!(contentType == X509ContentType.Cert || contentType == X509ContentType.SerializedCert || contentType == X509ContentType.Pkcs12)) throw new CryptographicException(SR.Cryptography_X509_InvalidContentType); } internal const X509KeyStorageFlags KeyStorageFlagsAll = X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserProtected | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.EphemeralKeySet; } }
// ContactsEditorViewModel.cs // using System; using System.Collections.Generic; using Xrm.Sdk; using KnockoutApi; using Slick; using Client.TimeSheet.ViewModel; using SparkleXrm.GridEditor; using SparkleXrm; using Client.ContactEditor.ViewModels; using Client.ContactEditor.Model; using Xrm; using System.Runtime.CompilerServices; namespace Client.ContactEditor.ViewModels { public class ContactsEditorViewModel :ViewModelBase { #region Fields public EntityDataViewModel Contacts; public Observable<ObservableContact> SelectedContact; #endregion #region Constructors public ContactsEditorViewModel() { SelectedContact = (Observable<ObservableContact>)ValidatedObservableFactory.ValidatedObservable(new ObservableContact()); Contacts = new EntityDataViewModel(10, typeof(Contact),true); Contacts.OnSelectedRowsChanged += OnSelectedRowsChanged; Contacts.FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' returntotalrecordcount='true' no-lock='true' distinct='false' count='{0}' paging-cookie='{1}' page='{2}'> <entity name='contact'> <attribute name='firstname' /> <attribute name='lastname' /> <attribute name='telephone1' /> <attribute name='birthdate' /> <attribute name='accountrolecode' /> <attribute name='parentcustomerid'/> <attribute name='transactioncurrencyid'/> <attribute name='creditlimit'/> <attribute name='numberofchildren'/> <attribute name='contactid' /> <attribute name='ownerid'/>{3} </entity> </fetch>"; // Register validation ContactValidation.Register(Contacts.ValidationBinder); ContactValidation.Register(new ObservableValidationBinder(this.SelectedContact)); } #endregion #region Events public void OnSelectedRowsChanged() { SelectedRange[] selectedContacts = Contacts.GetSelectedRows(); if (selectedContacts.Length>0) { SelectedContact.GetValue().SetValue((Contact)Contacts.GetItem(selectedContacts[0].FromRow.Value)); } else SelectedContact.GetValue().SetValue(null); } #endregion #region Commands private DependentObservable<bool> _canAddNew; public DependentObservable<bool> CanAddNew() { if (_canAddNew==null) { DependentObservableOptions<bool> IsRegisterFormValidDependantProperty = new DependentObservableOptions<bool>(); IsRegisterFormValidDependantProperty.Model = this; IsRegisterFormValidDependantProperty.GetValueFunction = new Func<bool>(delegate { EntityStates state = SelectedContact.GetValue().EntityState.GetValue(); if (state != null) { return state != EntityStates.Created; } else return true; }); _canAddNew = Knockout.DependentObservable<bool>(IsRegisterFormValidDependantProperty); } return _canAddNew; } private Action _saveSelectedContact; public Action SaveSelectedContact() { if (_saveSelectedContact == null) { _saveSelectedContact = delegate() { if (((IValidatedObservable)SelectedContact).IsValid()) { Contact contact = SelectedContact.GetValue().Commit(); ObservableContact selectedContact = SelectedContact.GetValue(); if (selectedContact.EntityState.GetValue() == EntityStates.Created) { this.Contacts.AddItem(contact); // Move to the last page PagingInfo paging = this.Contacts.GetPagingInfo(); SelectedRange[] newRow = new SelectedRange[1]; newRow[0] = new SelectedRange(); newRow[0].FromRow = paging.TotalRows - ((paging.TotalPages - 1) * paging.PageSize)-1; this.Contacts.RaiseOnSelectedRowsChanged(newRow); selectedContact.EntityState.SetValue(EntityStates.Changed); } else { Contacts.Refresh(); } } else { Script.Literal("{0}.errors.showAllMessages()", SelectedContact); } }; } return _saveSelectedContact; } private Action _addNewContact; public Action AddNewContact() { if (_addNewContact == null) { _addNewContact = delegate() { Contact newContact = new Contact(); newContact.EntityState = EntityStates.Created; this.SelectedContact.GetValue().SetValue(newContact); Script.Literal("{0}.errors.showAllMessages(false)", SelectedContact); }; } return _addNewContact; } private Action _resetCommand; public Action ResetCommand() { if (_resetCommand == null) { _resetCommand = delegate() { bool confirmed = Script.Confirm(String.Format("Are you sure you want to reset the grid? This will loose any values you have edited.")); if (!confirmed) return; Contacts.Reset(); Contacts.Refresh(); }; } return _resetCommand; } private Action _saveCommand; public Action SaveCommand() { if (_saveCommand == null) { _saveCommand = delegate() { List<Contact> dirtyCollection = new List<Contact>(); foreach (Entity item in this.Contacts.Data) { if (item!=null && item.EntityState!=EntityStates.Unchanged) dirtyCollection.Add((Contact)item); } int itemCount = dirtyCollection.Count; if (itemCount == 0) return; bool confirmed = Script.Confirm(String.Format("Are you sure that you want to save the {0} records edited in the Grid?", itemCount)); if (!confirmed) return; IsBusy.SetValue(true); string errorMessage = ""; SaveNextRecord(dirtyCollection, errorMessage, delegate() { if (errorMessage.Length > 0) { Script.Alert("One or more records failed to save.\nPlease contact your System Administrator.\n\n" + errorMessage); } else { Script.Alert("Save Complete!"); } Contacts.Refresh(); IsBusy.SetValue(false); }); }; } return _saveCommand; } public void TransactionCurrencySearchCommand(string term, Action<EntityCollection> callback) { // Get the option set values string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='transactioncurrency'> <attribute name='transactioncurrencyid' /> <attribute name='currencyname' /> <attribute name='isocurrencycode' /> <attribute name='currencysymbol' /> <attribute name='exchangerate' /> <attribute name='currencyprecision' /> <order attribute='currencyname' descending='false' /> <filter type='and'> <condition attribute='currencyname' operator='like' value='%{0}%' /> </filter> </entity> </fetch>"; fetchXml = string.Format(fetchXml, XmlHelper.Encode(term)); OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result) { EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity)); callback(fetchResult); }); } [PreserveCase] public void AddNewAccountInLine(object item) { OpenEntityFormOptions newRecordOptions = new OpenEntityFormOptions(); newRecordOptions.OpenInNewWindow = true; Utility.OpenEntityForm2("account", null, null, newRecordOptions); } public void OwnerSearchCommand(string term, Action<EntityCollection> callback) { Dictionary<string, string> searchTypes = new Dictionary<string, string>(); searchTypes["systemuser"] = "fullname"; searchTypes["team"] = "name"; int resultsBack = 0; List<Entity> mergedEntities = new List<Entity>(); Action<EntityCollection> result = delegate(EntityCollection fetchResult) { resultsBack++; // Merge in the results mergedEntities.AddRange((Entity[])(object)fetchResult.Entities.Items()); mergedEntities.Sort(delegate(Entity x, Entity y) { return string.Compare(x.GetAttributeValueString("name"), y.GetAttributeValueString("name")); }); if (resultsBack == searchTypes.Count) { EntityCollection results = new EntityCollection(mergedEntities); callback(results); } }; foreach (string entity in searchTypes.Keys) { SearchRecords(term, result, entity, searchTypes[entity]); } } [PreserveCase] public void AccountSearchCommand(string term, Action<EntityCollection> callback) { string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='account'> <attribute name='accountid' /> <attribute name='name' /> <attribute name='address1_city' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='name' operator='like' value='%{0}%' /> </filter> </entity> </fetch>"; fetchXml = string.Format(fetchXml, XmlHelper.Encode(term)); OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result) { EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity)); callback(fetchResult); }); } private void SearchRecords(string term, Action<EntityCollection> callback, string entityType, string entityNameAttribute) { string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' no-lock='true' count='25'> <entity name='{1}'> <attribute name='{2}' alias='name' /> <order attribute='{2}' descending='false' /> <filter type='and'> <condition attribute='{2}' operator='like' value='%{0}%' /> </filter> </entity> </fetch>"; fetchXml = string.Format(fetchXml, XmlHelper.Encode(term), entityType, entityNameAttribute); OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result) { EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity)); callback(fetchResult); }); } public void ReportError(Exception ex) { } private void SaveNextRecord(List<Contact> dirtyCollection,string errorMessage,Action callBack) { Contact contactToSave = dirtyCollection[0]; if (contactToSave.ContactId == null) { OrganizationServiceProxy.BeginCreate(contactToSave, delegate(object r) { try { Guid newID = OrganizationServiceProxy.EndCreate(r); contactToSave.ContactId = newID; contactToSave.EntityState = EntityStates.Unchanged; } catch (Exception ex) { // Something when wrong with create errorMessage = errorMessage + ex.Message + "\n"; } dirtyCollection.Remove(contactToSave); if (dirtyCollection.Count == 0) callBack(); else SaveNextRecord(dirtyCollection, errorMessage, callBack); }); } else { OrganizationServiceProxy.BeginUpdate(contactToSave, delegate(object r) { try { OrganizationServiceProxy.EndUpdate(r); contactToSave.EntityState = EntityStates.Unchanged; if (contactToSave.OwnerId != null) { // Assign the record OrganizationServiceProxy.RegisterExecuteMessageResponseType("Assign", typeof(AssignResponse)); AssignRequest assignRequest = new AssignRequest(); assignRequest.Target = contactToSave.ToEntityReference(); assignRequest.Assignee = contactToSave.OwnerId; OrganizationServiceProxy.Execute(assignRequest); } } catch (Exception ex) { // Something when wrong errorMessage = errorMessage + ex.Message + "\n"; } dirtyCollection.Remove(contactToSave); if (dirtyCollection.Count == 0) callBack(); else SaveNextRecord(dirtyCollection, errorMessage, callBack); }); } } #endregion #region Methods public void Init() { Contacts.SortBy(new SortCol("lastname", true)); Contacts.Refresh(); } #endregion } }
using System; using System.Data; using Csla; using Csla.Data; using Invoices.DataAccess; namespace Invoices.Business { /// <summary> /// InvoiceEdit (editable root object).<br/> /// This is a generated <see cref="InvoiceEdit"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="InvoiceLines"/> of type <see cref="InvoiceLineCollection"/> (1:M relation to <see cref="InvoiceLineItem"/>) /// </remarks> [Serializable] public partial class InvoiceEdit : BusinessBase<InvoiceEdit> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="InvoiceId"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<Guid> InvoiceIdProperty = RegisterProperty<Guid>(p => p.InvoiceId, "Invoice Id"); /// <summary> /// The invoice internal identification /// </summary> /// <value>The Invoice Id.</value> public Guid InvoiceId { get { return GetProperty(InvoiceIdProperty); } set { SetProperty(InvoiceIdProperty, value); } } /// <summary> /// Maintains metadata about <see cref="InvoiceNumber"/> property. /// </summary> public static readonly PropertyInfo<string> InvoiceNumberProperty = RegisterProperty<string>(p => p.InvoiceNumber, "Invoice Number"); /// <summary> /// The public invoice number /// </summary> /// <value>The Invoice Number.</value> public string InvoiceNumber { get { return GetProperty(InvoiceNumberProperty); } set { SetProperty(InvoiceNumberProperty, value); } } /// <summary> /// Maintains metadata about <see cref="CustomerId"/> property. /// </summary> public static readonly PropertyInfo<string> CustomerIdProperty = RegisterProperty<string>(p => p.CustomerId, "Customer Id"); /// <summary> /// Gets or sets the Customer Id. /// </summary> /// <value>The Customer Id.</value> public string CustomerId { get { return GetProperty(CustomerIdProperty); } set { SetProperty(CustomerIdProperty, value); } } /// <summary> /// Maintains metadata about <see cref="InvoiceDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> InvoiceDateProperty = RegisterProperty<SmartDate>(p => p.InvoiceDate, "Invoice Date"); /// <summary> /// Gets or sets the Invoice Date. /// </summary> /// <value>The Invoice Date.</value> public string InvoiceDate { get { return GetPropertyConvert<SmartDate, string>(InvoiceDateProperty); } set { SetPropertyConvert<SmartDate, string>(InvoiceDateProperty, value); } } /// <summary> /// Maintains metadata about <see cref="TotalAmount"/> property. /// </summary> public static readonly PropertyInfo<decimal> TotalAmountProperty = RegisterProperty<decimal>(p => p.TotalAmount, "Total Amount"); /// <summary> /// Computed invoice total amount /// </summary> /// <value>The Total Amount.</value> public decimal TotalAmount { get { return GetProperty(TotalAmountProperty); } set { SetProperty(TotalAmountProperty, value); } } /// <summary> /// Maintains metadata about <see cref="CreateDate"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date"); /// <summary> /// Gets the Create Date. /// </summary> /// <value>The Create Date.</value> public SmartDate CreateDate { get { return GetProperty(CreateDateProperty); } } /// <summary> /// Maintains metadata about <see cref="CreateUser"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<int> CreateUserProperty = RegisterProperty<int>(p => p.CreateUser, "Create User"); /// <summary> /// Gets the Create User. /// </summary> /// <value>The Create User.</value> public int CreateUser { get { return GetProperty(CreateUserProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeDate"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date"); /// <summary> /// Gets the Change Date. /// </summary> /// <value>The Change Date.</value> public SmartDate ChangeDate { get { return GetProperty(ChangeDateProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeUser"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<int> ChangeUserProperty = RegisterProperty<int>(p => p.ChangeUser, "Change User"); /// <summary> /// Gets the Change User. /// </summary> /// <value>The Change User.</value> public int ChangeUser { get { return GetProperty(ChangeUserProperty); } } /// <summary> /// Maintains metadata about <see cref="RowVersion"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version"); /// <summary> /// Gets the Row Version. /// </summary> /// <value>The Row Version.</value> public byte[] RowVersion { get { return GetProperty(RowVersionProperty); } } /// <summary> /// Maintains metadata about child <see cref="InvoiceLines"/> property. /// </summary> public static readonly PropertyInfo<InvoiceLineCollection> InvoiceLinesProperty = RegisterProperty<InvoiceLineCollection>(p => p.InvoiceLines, "Invoice Lines", RelationshipTypes.Child); /// <summary> /// Gets the Invoice Lines ("parent load" child property). /// </summary> /// <value>The Invoice Lines.</value> public InvoiceLineCollection InvoiceLines { get { return GetProperty(InvoiceLinesProperty); } private set { LoadProperty(InvoiceLinesProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="InvoiceEdit"/> object. /// </summary> /// <returns>A reference to the created <see cref="InvoiceEdit"/> object.</returns> public static InvoiceEdit NewInvoiceEdit() { return DataPortal.Create<InvoiceEdit>(); } /// <summary> /// Factory method. Loads a <see cref="InvoiceEdit"/> object, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId parameter of the InvoiceEdit to fetch.</param> /// <returns>A reference to the fetched <see cref="InvoiceEdit"/> object.</returns> public static InvoiceEdit GetInvoiceEdit(Guid invoiceId) { return DataPortal.Fetch<InvoiceEdit>(invoiceId); } /// <summary> /// Factory method. Deletes a <see cref="InvoiceEdit"/> object, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId of the InvoiceEdit to delete.</param> public static void DeleteInvoiceEdit(Guid invoiceId) { DataPortal.Delete<InvoiceEdit>(invoiceId); } /// <summary> /// Factory method. Asynchronously creates a new <see cref="InvoiceEdit"/> object. /// </summary> /// <param name="callback">The completion callback method.</param> public static void NewInvoiceEdit(EventHandler<DataPortalResult<InvoiceEdit>> callback) { DataPortal.BeginCreate<InvoiceEdit>(callback); } /// <summary> /// Factory method. Asynchronously loads a <see cref="InvoiceEdit"/> object, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId parameter of the InvoiceEdit to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetInvoiceEdit(Guid invoiceId, EventHandler<DataPortalResult<InvoiceEdit>> callback) { DataPortal.BeginFetch<InvoiceEdit>(invoiceId, callback); } /// <summary> /// Factory method. Asynchronously deletes a <see cref="InvoiceEdit"/> object, based on given parameters. /// </summary> /// <param name="invoiceId">The InvoiceId of the InvoiceEdit to delete.</param> /// <param name="callback">The completion callback method.</param> public static void DeleteInvoiceEdit(Guid invoiceId, EventHandler<DataPortalResult<InvoiceEdit>> callback) { DataPortal.BeginDelete<InvoiceEdit>(invoiceId, callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="InvoiceEdit"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public InvoiceEdit() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="InvoiceEdit"/> object properties. /// </summary> [RunLocal] protected override void DataPortal_Create() { LoadProperty(InvoiceIdProperty, Guid.NewGuid()); LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now)); LoadProperty(CreateUserProperty, Security.UserInformation.UserId); LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty)); LoadProperty(ChangeUserProperty, ReadProperty(CreateUserProperty)); LoadProperty(InvoiceLinesProperty, DataPortal.CreateChild<InvoiceLineCollection>()); var args = new DataPortalHookArgs(); OnCreate(args); base.DataPortal_Create(); } /// <summary> /// Loads a <see cref="InvoiceEdit"/> object from the database, based on given criteria. /// </summary> /// <param name="invoiceId">The Invoice Id.</param> protected void DataPortal_Fetch(Guid invoiceId) { var args = new DataPortalHookArgs(invoiceId); OnFetchPre(args); using (var dalManager = DalFactoryInvoices.GetManager()) { var dal = dalManager.GetProvider<IInvoiceEditDal>(); var data = dal.Fetch(invoiceId); Fetch(data); } OnFetchPost(args); // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); FetchChildren(dr); } } } /// <summary> /// Loads a <see cref="InvoiceEdit"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(InvoiceIdProperty, dr.GetGuid("InvoiceId")); LoadProperty(InvoiceNumberProperty, dr.GetString("InvoiceNumber")); LoadProperty(CustomerIdProperty, dr.GetString("CustomerId")); LoadProperty(InvoiceDateProperty, dr.GetSmartDate("InvoiceDate", true)); LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true)); LoadProperty(CreateUserProperty, dr.GetInt32("CreateUser")); LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true)); LoadProperty(ChangeUserProperty, dr.GetInt32("ChangeUser")); LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void FetchChildren(SafeDataReader dr) { dr.NextResult(); LoadProperty(InvoiceLinesProperty, DataPortal.FetchChild<InvoiceLineCollection>(dr)); } /// <summary> /// Inserts a new <see cref="InvoiceEdit"/> object in the database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { SimpleAuditTrail(); using (var dalManager = DalFactoryInvoices.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IInvoiceEditDal>(); using (BypassPropertyChecks) { LoadProperty(RowVersionProperty, dal.Insert( InvoiceId, InvoiceNumber, CustomerId, ReadProperty(InvoiceDateProperty), CreateDate, CreateUser, ChangeDate, ChangeUser )); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="InvoiceEdit"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { SimpleAuditTrail(); using (var dalManager = DalFactoryInvoices.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IInvoiceEditDal>(); using (BypassPropertyChecks) { LoadProperty(RowVersionProperty, dal.Update( InvoiceId, InvoiceNumber, CustomerId, ReadProperty(InvoiceDateProperty), ChangeDate, ChangeUser, RowVersion )); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } private void SimpleAuditTrail() { LoadProperty(ChangeDateProperty, DateTime.Now); LoadProperty(ChangeUserProperty, Security.UserInformation.UserId); if (IsNew) { LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty)); LoadProperty(CreateUserProperty, ReadProperty(ChangeUserProperty)); } } /// <summary> /// Self deletes the <see cref="InvoiceEdit"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_DeleteSelf() { DataPortal_Delete(InvoiceId); } /// <summary> /// Deletes the <see cref="InvoiceEdit"/> object from database. /// </summary> /// <param name="invoiceId">The Invoice Id.</param> [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(Guid invoiceId) { // audit the object, just in case soft delete is used on this object SimpleAuditTrail(); using (var dalManager = DalFactoryInvoices.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IInvoiceEditDal>(); using (BypassPropertyChecks) { dal.Delete(invoiceId); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Threading.Tasks; using System.Web; using System.Net; using System.Text; using System.IO; using System.Threading; using System.Collections.Generic; using System.Security.Cryptography; using System.ComponentModel; using SteamBot.SteamGroups; using SteamKit2; using SteamTrade; using SteamKit2.Internal; namespace SteamBot { public class Bot { public string BotControlClass; // If the bot is logged in fully or not. This is only set // when it is. public bool IsLoggedIn = false; // The bot's display name. Changing this does not mean that // the bot's name will change. public string DisplayName { get; private set; } // The response to all chat messages sent to it. public string ChatResponse; // A list of SteamIDs that this bot recognizes as admins. public ulong[] Admins; public SteamFriends SteamFriends; public SteamClient SteamClient; public SteamTrading SteamTrade; public SteamUser SteamUser; public SteamGameCoordinator SteamGameCoordinator; // The current trade; if the bot is not in a trade, this is // null. public Trade CurrentTrade; public bool IsDebugMode = false; // The log for the bot. This logs with the bot's display name. public Log log; public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id); public UserHandlerCreator CreateHandler; Dictionary<ulong, UserHandler> userHandlers = new Dictionary<ulong, UserHandler>(); List<SteamID> friends = new List<SteamID>(); // List of Steam groups the bot is in. private readonly List<SteamID> groups = new List<SteamID>(); // The maximum amount of time the bot will trade for. public int MaximumTradeTime { get; private set; } // The maximum amount of time the bot will wait in between // trade actions. public int MaximiumActionGap { get; private set; } //The current game that the bot is playing, for posterity. public int CurrentGame = 0; // The Steam Web API key. public string apiKey; // The prefix put in the front of the bot's display name. string DisplayNamePrefix; // Log level to use for this bot Log.LogLevel LogLevel; // The number, in milliseconds, between polls for the trade. int TradePollingInterval; public string MyLoginKey; string sessionId; string token; bool isprocess; public bool IsRunning = false; public string AuthCode { get; set; } SteamUser.LogOnDetails logOnDetails; TradeManager tradeManager; private Task<Inventory> myInventoryTask; public Inventory MyInventory { get { myInventoryTask.Wait(); return myInventoryTask.Result; } } private BackgroundWorker backgroundWorker; public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false) { logOnDetails = new SteamUser.LogOnDetails { Username = config.Username, Password = config.Password }; DisplayName = config.DisplayName; ChatResponse = config.ChatResponse; MaximumTradeTime = config.MaximumTradeTime; MaximiumActionGap = config.MaximumActionGap; DisplayNamePrefix = config.DisplayNamePrefix; TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval; Admins = config.Admins; this.apiKey = apiKey; this.isprocess = process; try { LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true); } catch (ArgumentException) { Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'"); LogLevel = Log.LogLevel.Info; } log = new Log (config.LogFile, this.DisplayName, LogLevel); CreateHandler = handlerCreator; BotControlClass = config.BotControlClass; // Hacking around https ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate; log.Debug ("Initializing Steam Bot..."); SteamClient = new SteamClient(); SteamTrade = SteamClient.GetHandler<SteamTrading>(); SteamUser = SteamClient.GetHandler<SteamUser>(); SteamFriends = SteamClient.GetHandler<SteamFriends>(); SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>(); backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = true }; backgroundWorker.DoWork += BackgroundWorkerOnDoWork; backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted; backgroundWorker.RunWorkerAsync(); } /// <summary> /// Occurs when the bot needs the SteamGuard authentication code. /// </summary> /// <remarks> /// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/> /// </remarks> public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired; /// <summary> /// Starts the callback thread and connects to Steam via SteamKit2. /// </summary> /// <remarks> /// THIS NEVER RETURNS. /// </remarks> /// <returns><c>true</c>. See remarks</returns> public bool StartBot() { IsRunning = true; log.Info("Connecting..."); if (!backgroundWorker.IsBusy) // background worker is not running backgroundWorker.RunWorkerAsync(); SteamClient.Connect(); log.Success("Done Loading Bot!"); return true; // never get here } /// <summary> /// Disconnect from the Steam network and stop the callback /// thread. /// </summary> public void StopBot() { IsRunning = false; log.Debug("Trying to shut down bot thread."); SteamClient.Disconnect(); backgroundWorker.CancelAsync(); } /// <summary> /// Creates a new trade with the given partner. /// </summary> /// <returns> /// <c>true</c>, if trade was opened, /// <c>false</c> if there is another trade that must be closed first. /// </returns> public bool OpenTrade (SteamID other) { if (CurrentTrade != null) return false; SteamTrade.Trade(other); return true; } /// <summary> /// Closes the current active trade. /// </summary> public void CloseTrade() { if (CurrentTrade == null) return; UnsubscribeTrade (GetUserHandler (CurrentTrade.OtherSID), CurrentTrade); tradeManager.StopTrade (); CurrentTrade = null; } void OnTradeTimeout(object sender, EventArgs args) { // ignore event params and just null out the trade. GetUserHandler (CurrentTrade.OtherSID).OnTradeTimeout(); } public void HandleBotCommand(string command) { try { GetUserHandler(SteamClient.SteamID).OnBotCommand(command); } catch (ObjectDisposedException e) { // Writing to console because odds are the error was caused by a disposed log. Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); if (!this.IsRunning) { Console.WriteLine("The Bot is no longer running and could not write to the log. Try Starting this bot first."); } } catch (Exception e) { Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); } } bool HandleTradeSessionStart (SteamID other) { if (CurrentTrade != null) return false; try { tradeManager.InitializeTrade(SteamUser.SteamID, other); CurrentTrade = tradeManager.CreateTrade (SteamUser.SteamID, other); CurrentTrade.OnClose += CloseTrade; SubscribeTrade(CurrentTrade, GetUserHandler(other)); tradeManager.StartTradeThread(CurrentTrade); return true; } catch (SteamTrade.Exceptions.InventoryFetchException ie) { // we shouldn't get here because the inv checks are also // done in the TradeProposedCallback handler. string response = String.Empty; if (ie.FailingSteamId.ConvertToUInt64() == other.ConvertToUInt64()) { response = "Trade failed. Could not correctly fetch your backpack. Either the inventory is inaccessible or your backpack is private."; } else { response = "Trade failed. Could not correctly fetch my backpack."; } SteamFriends.SendChatMessage(other, EChatEntryType.ChatMsg, response); log.Info ("Bot sent other: " + response); CurrentTrade = null; return false; } } public void SetGamePlaying(int id) { var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed); if (id != 0) gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed { game_id = new GameID(id), }); SteamClient.Send(gamePlaying); CurrentGame = id; } void HandleSteamMessage (CallbackMsg msg) { log.Debug(msg.ToString()); #region Login msg.Handle<SteamClient.ConnectedCallback> (callback => { log.Debug ("Connection Callback: " + callback.Result); if (callback.Result == EResult.OK) { UserLogOn(); } else { log.Error ("Failed to connect to Steam Community, trying again..."); SteamClient.Connect (); } }); msg.Handle<SteamUser.LoggedOnCallback> (callback => { log.Debug ("Logged On Callback: " + callback.Result); if (callback.Result == EResult.OK) { MyLoginKey = callback.WebAPIUserNonce; } else { log.Error ("Login Error: " + callback.Result); } if (callback.Result == EResult.AccountLogonDenied) { log.Interface ("This account is SteamGuard enabled. Enter the code via the `auth' command."); // try to get the steamguard auth code from the event callback var eva = new SteamGuardRequiredEventArgs(); FireOnSteamGuardRequired(eva); if (!String.IsNullOrEmpty(eva.SteamGuard)) logOnDetails.AuthCode = eva.SteamGuard; else logOnDetails.AuthCode = Console.ReadLine(); } if (callback.Result == EResult.InvalidLoginAuthCode) { log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command."); logOnDetails.AuthCode = Console.ReadLine(); } }); msg.Handle<SteamUser.LoginKeyCallback> (callback => { while (true) { bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token, MyLoginKey); if (authd) { log.Success ("User Authenticated!"); tradeManager = new TradeManager(apiKey, sessionId, token); tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval); tradeManager.OnTimeout += OnTradeTimeout; break; } else { log.Warn ("Authentication failed, retrying in 2s..."); Thread.Sleep (2000); } } if (Trade.CurrentSchema == null) { log.Info ("Downloading Schema..."); Trade.CurrentSchema = Schema.FetchSchema (apiKey); log.Success ("Schema Downloaded!"); } SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName); SteamFriends.SetPersonaState (EPersonaState.Online); log.Success ("Steam Bot Logged In Completely!"); IsLoggedIn = true; GetUserHandler(SteamClient.SteamID).OnLoginCompleted(); }); // handle a special JobCallback differently than the others if (msg.IsType<SteamClient.JobCallback<SteamUser.UpdateMachineAuthCallback>>()) { msg.Handle<SteamClient.JobCallback<SteamUser.UpdateMachineAuthCallback>>( jobCallback => OnUpdateMachineAuthCallback(jobCallback.Callback, jobCallback.JobID) ); } #endregion #region Friends msg.Handle<SteamFriends.FriendsListCallback>(callback => { foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList) { if (friend.SteamID.AccountType == EAccountType.Clan) { if (!groups.Contains(friend.SteamID)) { groups.Add(friend.SteamID); if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnGroupAdd()) { AcceptGroupInvite(friend.SteamID); } else { DeclineGroupInvite(friend.SteamID); } } } else { if (friend.Relationship == EFriendRelationship.None) { groups.Remove(friend.SteamID); } } } else if (friend.SteamID.AccountType != EAccountType.Clan) { if (!friends.Contains(friend.SteamID)) { friends.Add(friend.SteamID); if (friend.Relationship == EFriendRelationship.RequestRecipient && GetUserHandler(friend.SteamID).OnFriendAdd()) { SteamFriends.AddFriend(friend.SteamID); } } else { if (friend.Relationship == EFriendRelationship.None) { friends.Remove(friend.SteamID); GetUserHandler(friend.SteamID).OnFriendRemove(); RemoveUserHandler(friend.SteamID); } } } } }); msg.Handle<SteamFriends.FriendMsgCallback> (callback => { EChatEntryType type = callback.EntryType; if (callback.EntryType == EChatEntryType.ChatMsg) { log.Info (String.Format ("Chat Message from {0}: {1}", SteamFriends.GetFriendPersonaName (callback.Sender), callback.Message )); GetUserHandler(callback.Sender).OnMessage(callback.Message, type); } }); #endregion #region Group Chat msg.Handle<SteamFriends.ChatMsgCallback>(callback => { GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message); }); #endregion #region Trading msg.Handle<SteamTrading.SessionStartCallback> (callback => { bool started = HandleTradeSessionStart (callback.OtherClient); if (!started) log.Error ("Could not start the trade session."); else log.Debug ("SteamTrading.SessionStartCallback handled successfully. Trade Opened."); }); msg.Handle<SteamTrading.TradeProposedCallback> (callback => { try { tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient); } catch (WebException we) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade error: " + we.Message); SteamTrade.RespondToTrade(callback.TradeID, false); return; } catch (Exception) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade declined. Could not correctly fetch your backpack."); SteamTrade.RespondToTrade(callback.TradeID, false); return; } //if (tradeManager.OtherInventory.IsPrivate) //{ // SteamFriends.SendChatMessage(callback.OtherClient, // EChatEntryType.ChatMsg, // "Trade declined. Your backpack cannot be private."); // SteamTrade.RespondToTrade (callback.TradeID, false); // return; //} if (CurrentTrade == null && GetUserHandler (callback.OtherClient).OnTradeRequest ()) SteamTrade.RespondToTrade (callback.TradeID, true); else SteamTrade.RespondToTrade (callback.TradeID, false); }); msg.Handle<SteamTrading.TradeResultCallback> (callback => { if (callback.Response == EEconTradeResponse.Accepted) { log.Debug ("Trade Status: " + callback.Response); log.Info ("Trade Accepted!"); GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString()); } else { log.Warn ("Trade failed: " + callback.Response); CloseTrade (); GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString()); } }); #endregion #region Disconnect msg.Handle<SteamUser.LoggedOffCallback> (callback => { IsLoggedIn = false; log.Warn ("Logged Off: " + callback.Result); }); msg.Handle<SteamClient.DisconnectedCallback> (callback => { IsLoggedIn = false; CloseTrade (); log.Warn ("Disconnected from Steam Network!"); SteamClient.Connect (); }); #endregion } void UserLogOn() { // get sentry file which has the machine hw info saved // from when a steam guard code was entered Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); FileInfo fi = new FileInfo(System.IO.Path.Combine("sentryfiles",String.Format("{0}.sentryfile", logOnDetails.Username))); if (fi.Exists && fi.Length > 0) logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName)); else logOnDetails.SentryFileHash = null; SteamUser.LogOn(logOnDetails); } UserHandler GetUserHandler(SteamID sid) { if (!userHandlers.ContainsKey(sid)) { userHandlers[sid.ConvertToUInt64()] = CreateHandler(this, sid); } return userHandlers[sid.ConvertToUInt64()]; } void RemoveUserHandler(SteamID sid) { if (userHandlers.ContainsKey(sid)) { userHandlers.Remove(sid); } } static byte [] SHAHash (byte[] input) { SHA1Managed sha = new SHA1Managed(); byte[] output = sha.ComputeHash( input ); sha.Clear(); return output; } void OnUpdateMachineAuthCallback (SteamUser.UpdateMachineAuthCallback machineAuth, JobID jobId) { byte[] hash = SHAHash (machineAuth.Data); Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); File.WriteAllBytes (System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data); var authResponse = new SteamUser.MachineAuthDetails { BytesWritten = machineAuth.BytesToWrite, FileName = machineAuth.FileName, FileSize = machineAuth.BytesToWrite, Offset = machineAuth.Offset, SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs LastError = 0, // result from win32 GetLastError Result = EResult.OK, // if everything went okay, otherwise ~who knows~ JobID = jobId, // so we respond to the correct server job }; // send off our response SteamUser.SendMachineAuthResponse (authResponse); } /// <summary> /// Gets the bot's inventory and stores it in MyInventory. /// </summary> /// <example> This sample shows how to find items in the bot's inventory from a user handler. /// <code> /// Bot.GetInventory(); // Get the inventory first /// foreach (var item in Bot.MyInventory.Items) /// { /// if (item.Defindex == 5021) /// { /// // Bot has a key in its inventory /// } /// } /// </code> /// </example> public void GetInventory() { myInventoryTask = Task.Factory.StartNew(() => Inventory.FetchInventory(SteamUser.SteamID, apiKey)); } /// <summary> /// Subscribes all listeners of this to the trade. /// </summary> public void SubscribeTrade (Trade trade, UserHandler handler) { trade.OnSuccess += handler.OnTradeSuccess; trade.OnClose += handler.OnTradeClose; trade.OnError += handler.OnTradeError; //trade.OnTimeout += OnTradeTimeout; trade.OnAfterInit += handler.OnTradeInit; trade.OnUserAddItem += handler.OnTradeAddItem; trade.OnUserRemoveItem += handler.OnTradeRemoveItem; trade.OnMessage += handler.OnTradeMessage; trade.OnUserSetReady += handler.OnTradeReadyHandler; trade.OnUserAccept += handler.OnTradeAcceptHandler; } /// <summary> /// Unsubscribes all listeners of this from the current trade. /// </summary> public void UnsubscribeTrade (UserHandler handler, Trade trade) { trade.OnSuccess -= handler.OnTradeSuccess; trade.OnClose -= handler.OnTradeClose; trade.OnError -= handler.OnTradeError; //Trade.OnTimeout -= OnTradeTimeout; trade.OnAfterInit -= handler.OnTradeInit; trade.OnUserAddItem -= handler.OnTradeAddItem; trade.OnUserRemoveItem -= handler.OnTradeRemoveItem; trade.OnMessage -= handler.OnTradeMessage; trade.OnUserSetReady -= handler.OnTradeReadyHandler; trade.OnUserAccept -= handler.OnTradeAcceptHandler; } #region Background Worker Methods private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { if (runWorkerCompletedEventArgs.Error != null) { Exception ex = runWorkerCompletedEventArgs.Error; var s = string.Format("Unhandled exceptions in bot {0} callback thread: {1} {2}", DisplayName, Environment.NewLine, ex); log.Error(s); log.Info("This bot died. Stopping it.."); //backgroundWorker.RunWorkerAsync(); //Thread.Sleep(10000); StopBot(); //StartBot(); } log.Dispose(); } private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { CallbackMsg msg; while (!backgroundWorker.CancellationPending) { try { msg = SteamClient.WaitForCallback(true); HandleSteamMessage(msg); } catch (WebException e) { log.Error("URI: " + (e.Response != null && e.Response.ResponseUri != null ? e.Response.ResponseUri.ToString() : "unknown") + " >> " + e.ToString()); System.Threading.Thread.Sleep(45000);//Steam is down, retry in 45 seconds. } catch (Exception e) { log.Error(e.ToString()); log.Warn("Restarting bot..."); } } } #endregion Background Worker Methods private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e) { // Set to null in case this is another attempt this.AuthCode = null; EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired; if (handler != null) handler(this, e); else { while (true) { if (this.AuthCode != null) { e.SteamGuard = this.AuthCode; break; } Thread.Sleep(5); } } } #region Group Methods /// <summary> /// Accepts the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to accept the invite from.</param> private void AcceptGroupInvite(SteamID group) { var AcceptInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); AcceptInvite.Body.GroupID = group.ConvertToUInt64(); AcceptInvite.Body.AcceptInvite = true; this.SteamClient.Send(AcceptInvite); } /// <summary> /// Declines the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to decline the invite from.</param> private void DeclineGroupInvite(SteamID group) { var DeclineInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); DeclineInvite.Body.GroupID = group.ConvertToUInt64(); DeclineInvite.Body.AcceptInvite = false; this.SteamClient.Send(DeclineInvite); } /// <summary> /// Invites a use to the specified Steam Group /// </summary> /// <param name="user">SteamID of the user to invite.</param> /// <param name="groupId">SteamID of the group to invite the user to.</param> public void InviteUserToGroup(SteamID user, SteamID groupId) { var InviteUser = new ClientMsg<CMsgInviteUserToGroup>((int)EMsg.ClientInviteUserToClan); InviteUser.Body.GroupID = groupId.ConvertToUInt64(); InviteUser.Body.Invitee = user.ConvertToUInt64(); InviteUser.Body.UnknownInfo = true; this.SteamClient.Send(InviteUser); } #endregion } }
// // OracleConnection.cs // // Part of the Mono class libraries at // mcs/class/System.Data.OracleClient/System.Data.OracleClient // // Assembly: System.Data.OracleClient.dll // Namespace: System.Data.OracleClient // // Authors: // Daniel Morgan <danielmorgan@verizon.net> // Tim Coleman <tim@timcoleman.com> // Hubert FONGARNAND <informatique.internet@fiducial.fr> // // Copyright (C) Daniel Morgan, 2002, 2005 // Copyright (C) Tim Coleman, 2003 // Copyright (C) Hubert FONGARNAND, 2005 // // Original source code for setting ConnectionString // by Tim Coleman <tim@timcoleman.com> // // Copyright (C) Tim Coleman, 2002 // // Licensed under the MIT/X11 License. // using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.OracleClient.Oci; using System.Drawing.Design; using System.EnterpriseServices; using System.Text; namespace System.Data.OracleClient { internal struct OracleConnectionInfo { internal string Username; internal string Password; internal string Database; internal string ConnectionString; } [DefaultEvent ("InfoMessage")] public sealed class OracleConnection : Component, ICloneable, IDbConnection { #region Fields OciGlue oci; ConnectionState state; OracleConnectionInfo conInfo; OracleTransaction transaction = null; string connectionString = ""; OracleDataReader dataReader = null; bool pooling = true; static OracleConnectionPoolManager pools = new OracleConnectionPoolManager (); OracleConnectionPool pool; int minPoolSize = 0; int maxPoolSize = 100; #endregion // Fields #region Constructors public OracleConnection () { state = ConnectionState.Closed; } public OracleConnection (string connectionString) : this() { SetConnectionString (connectionString); } #endregion // Constructors #region Properties int IDbConnection.ConnectionTimeout { [MonoTODO] get { return -1; } } string IDbConnection.Database { [MonoTODO] get { return String.Empty; } } internal OracleDataReader DataReader { get { return dataReader; } set { dataReader = value; } } internal OciEnvironmentHandle Environment { get { return oci.Environment; } } internal OciErrorHandle ErrorHandle { get { return oci.ErrorHandle; } } internal OciServiceHandle ServiceContext { get { return oci.ServiceContext; } } internal OciSessionHandle Session { get { return oci.SessionHandle; } } [MonoTODO] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public string DataSource { get { return conInfo.Database; } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public ConnectionState State { get { return state; } } [DefaultValue ("")] [RecommendedAsConfigurable (true)] [RefreshProperties (RefreshProperties.All)] [Editor ("Microsoft.VSDesigner.Data.Oracle.Design.OracleConnectionStringEditor, " + Consts.AssemblyMicrosoft_VSDesigner, typeof(UITypeEditor))] public string ConnectionString { get { return connectionString; } set { SetConnectionString (value); } } [MonoTODO] [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public string ServerVersion { get { if (this.State != ConnectionState.Open) throw new System.InvalidOperationException ("Invalid operation. The connection is closed."); return GetOracleVersion (); } } internal string GetOracleVersion () { byte[] buffer = new Byte[256]; uint bufflen = (uint) buffer.Length; IntPtr sh = oci.ServiceContext; IntPtr eh = oci.ErrorHandle; OciCalls.OCIServerVersion (sh, eh, ref buffer, bufflen, OciHandleType.Service); // Get length of returned string int rsize = 0; IntPtr env = oci.Environment; OciCalls.OCICharSetToUnicode (env, null, buffer, out rsize); // Get string StringBuilder ret = new StringBuilder(rsize); OciCalls.OCICharSetToUnicode (env, ret, buffer, out rsize); return ret.ToString (); } internal OciGlue Oci { get { return oci; } } internal OracleTransaction Transaction { get { return transaction; } set { transaction = value; } } #endregion // Properties #region Methods public OracleTransaction BeginTransaction () { return BeginTransaction (IsolationLevel.ReadCommitted); } public OracleTransaction BeginTransaction (IsolationLevel il) { if (state == ConnectionState.Closed) throw new InvalidOperationException ("The connection is not open."); if (transaction != null) throw new InvalidOperationException ("OracleConnection does not support parallel transactions."); OciTransactionHandle transactionHandle = oci.CreateTransaction (); if (transactionHandle == null) throw new Exception("Error: Unable to start transaction"); else { transactionHandle.Begin (); transaction = new OracleTransaction (this, il, transactionHandle); } return transaction; } [MonoTODO] void IDbConnection.ChangeDatabase (string databaseName) { throw new NotImplementedException (); } public OracleCommand CreateCommand () { OracleCommand command = new OracleCommand (); command.Connection = this; return command; } [MonoTODO] object ICloneable.Clone () { OracleConnection con = new OracleConnection (); con.ConnectionString = this.ConnectionString; if (this.State == ConnectionState.Open) con.Open (); // TODO: what other properties need to be cloned? return con; } IDbTransaction IDbConnection.BeginTransaction () { return BeginTransaction (); } IDbTransaction IDbConnection.BeginTransaction (IsolationLevel iso) { return BeginTransaction (iso); } IDbCommand IDbConnection.CreateCommand () { return CreateCommand (); } void IDisposable.Dispose () { Dispose (true); GC.SuppressFinalize (this); } [MonoTODO] protected override void Dispose (bool disposing) { base.Dispose (disposing); } [MonoTODO] public void EnlistDistributedTransaction (ITransaction distributedTransaction) { throw new NotImplementedException (); } // Get NLS_DATE_FORMAT string from Oracle server internal string GetSessionDateFormat () { // 23 is 22 plus 1 for NUL terminated character // a DATE format has a max size of 22 return GetNlsInfo (Session, 23, OciNlsServiceType.DATEFORMAT); } // Get NLS Info // // handle = OciEnvironmentHandle or OciSessionHandle // bufflen = Length of byte buffer to allocate to retrieve the NLS info // item = OciNlsServiceType enum value // // if unsure how much you need, use OciNlsServiceType.MAXBUFSZ internal string GetNlsInfo (OciHandle handle, uint bufflen, OciNlsServiceType item) { byte[] buffer = new Byte[bufflen]; int st = OciCalls.OCINlsGetInfo (handle, ErrorHandle, ref buffer, bufflen, (ushort) item); // Get length of returned string int rsize = 0; OciCalls.OCICharSetToUnicode (Environment, null, buffer, out rsize); // Get string StringBuilder ret = new StringBuilder (rsize); OciCalls.OCICharSetToUnicode (Environment, ret, buffer, out rsize); return ret.ToString (); } public void Open () { if (!pooling) { oci = new OciGlue (); oci.CreateConnection (conInfo); } else { pool = pools.GetConnectionPool (conInfo, minPoolSize, maxPoolSize); oci = pool.GetConnection (); } state = ConnectionState.Open; CreateStateChange (ConnectionState.Closed, ConnectionState.Open); } internal void CreateInfoMessage (OciErrorInfo info) { OracleInfoMessageEventArgs a = new OracleInfoMessageEventArgs (info); OnInfoMessage (a); } private void OnInfoMessage (OracleInfoMessageEventArgs e) { if (InfoMessage != null) InfoMessage (this, e); } internal void CreateStateChange (ConnectionState original, ConnectionState current) { StateChangeEventArgs a = new StateChangeEventArgs (original, current); OnStateChange (a); } private void OnStateChange (StateChangeEventArgs e) { if (StateChange != null) StateChange (this, e); } public void Close () { if (transaction != null) transaction.Rollback (); if (!pooling) oci.Disconnect (); else if (pool != null) pool.ReleaseConnection (oci); state = ConnectionState.Closed; CreateStateChange (ConnectionState.Open, ConnectionState.Closed); } void SetConnectionString (string connectionString) { this.connectionString = connectionString; conInfo.Username = ""; conInfo.Database = ""; conInfo.Password = ""; if (connectionString == String.Empty) return; connectionString += ";"; NameValueCollection parameters = new NameValueCollection (); bool inQuote = false; bool inDQuote = false; string name = String.Empty; string value = String.Empty; StringBuilder sb = new StringBuilder (); foreach (char c in connectionString) { switch (c) { case '\'': inQuote = !inQuote; break; case '"' : inDQuote = !inDQuote; break; case ';' : if (!inDQuote && !inQuote) { if (name != String.Empty && name != null) { value = sb.ToString (); parameters [name.ToUpper ().Trim ()] = value.Trim (); } name = String.Empty; value = String.Empty; sb = new StringBuilder (); } else sb.Append (c); break; case '=' : if (!inDQuote && !inQuote) { name = sb.ToString (); sb = new StringBuilder (); } else sb.Append (c); break; default: sb.Append (c); break; } } SetProperties (parameters); conInfo.ConnectionString = connectionString; } private void SetProperties (NameValueCollection parameters) { string value; foreach (string name in parameters) { value = parameters[name]; switch (name) { case "UNICODE": break; case "ENLIST": break; case "CONNECTION LIFETIME": // TODO: break; case "INTEGRATED SECURITY": throw new NotImplementedException (); case "PERSIST SECURITY INFO": // TODO: break; case "MIN POOL SIZE": minPoolSize = int.Parse (value); break; case "MAX POOL SIZE": maxPoolSize = int.Parse (value); break; case "DATA SOURCE" : case "SERVER" : conInfo.Database = value; break; case "PASSWORD" : case "PWD" : conInfo.Password = value; break; case "UID" : case "USER ID" : conInfo.Username = value; break; case "POOLING" : switch (value.ToUpper ()) { case "YES": case "TRUE": pooling = true; break; case "NO": case "FALSE": pooling = false; break; default: throw new ArgumentException("Connection parameter not supported: '" + name + "'"); } break; default: throw new ArgumentException("Connection parameter not supported: '" + name + "'"); } } } #endregion // Methods public event OracleInfoMessageEventHandler InfoMessage; public event StateChangeEventHandler StateChange; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CSharp.RuntimeBinder.Errors { internal static class ErrorFacts { public static string GetMessage(ErrorCode code) { string codeStr; switch (code) { case ErrorCode.ERR_BadBinaryOps: codeStr = SR.BadBinaryOps; break; case ErrorCode.ERR_BadIndexLHS: codeStr = SR.BadIndexLHS; break; case ErrorCode.ERR_BadIndexCount: codeStr = SR.BadIndexCount; break; case ErrorCode.ERR_BadUnaryOp: codeStr = SR.BadUnaryOp; break; case ErrorCode.ERR_NoImplicitConv: codeStr = SR.NoImplicitConv; break; case ErrorCode.ERR_NoExplicitConv: codeStr = SR.NoExplicitConv; break; case ErrorCode.ERR_ConstOutOfRange: codeStr = SR.ConstOutOfRange; break; case ErrorCode.ERR_AmbigBinaryOps: codeStr = SR.AmbigBinaryOps; break; case ErrorCode.ERR_AmbigUnaryOp: codeStr = SR.AmbigUnaryOp; break; case ErrorCode.ERR_ValueCantBeNull: codeStr = SR.ValueCantBeNull; break; case ErrorCode.ERR_NoSuchMember: codeStr = SR.NoSuchMember; break; case ErrorCode.ERR_ObjectRequired: codeStr = SR.ObjectRequired; break; case ErrorCode.ERR_AmbigCall: codeStr = SR.AmbigCall; break; case ErrorCode.ERR_BadAccess: codeStr = SR.BadAccess; break; case ErrorCode.ERR_AssgLvalueExpected: codeStr = SR.AssgLvalueExpected; break; case ErrorCode.ERR_NoConstructors: codeStr = SR.NoConstructors; break; case ErrorCode.ERR_PropertyLacksGet: codeStr = SR.PropertyLacksGet; break; case ErrorCode.ERR_ObjectProhibited: codeStr = SR.ObjectProhibited; break; case ErrorCode.ERR_AssgReadonly: codeStr = SR.AssgReadonly; break; case ErrorCode.ERR_AssgReadonlyStatic: codeStr = SR.AssgReadonlyStatic; break; case ErrorCode.ERR_AssgReadonlyProp: codeStr = SR.AssgReadonlyProp; break; case ErrorCode.ERR_UnsafeNeeded: codeStr = SR.UnsafeNeeded; break; case ErrorCode.ERR_BadBoolOp: codeStr = SR.BadBoolOp; break; case ErrorCode.ERR_MustHaveOpTF: codeStr = SR.MustHaveOpTF; break; case ErrorCode.ERR_ConstOutOfRangeChecked: codeStr = SR.ConstOutOfRangeChecked; break; case ErrorCode.ERR_AmbigMember: codeStr = SR.AmbigMember; break; case ErrorCode.ERR_NoImplicitConvCast: codeStr = SR.NoImplicitConvCast; break; case ErrorCode.ERR_InaccessibleGetter: codeStr = SR.InaccessibleGetter; break; case ErrorCode.ERR_InaccessibleSetter: codeStr = SR.InaccessibleSetter; break; case ErrorCode.ERR_BadArity: codeStr = SR.BadArity; break; case ErrorCode.ERR_TypeArgsNotAllowed: codeStr = SR.TypeArgsNotAllowed; break; case ErrorCode.ERR_HasNoTypeVars: codeStr = SR.HasNoTypeVars; break; case ErrorCode.ERR_NewConstraintNotSatisfied: codeStr = SR.NewConstraintNotSatisfied; break; case ErrorCode.ERR_GenericConstraintNotSatisfiedRefType: codeStr = SR.GenericConstraintNotSatisfiedRefType; break; case ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum: codeStr = SR.GenericConstraintNotSatisfiedNullableEnum; break; case ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface: codeStr = SR.GenericConstraintNotSatisfiedNullableInterface; break; case ErrorCode.ERR_GenericConstraintNotSatisfiedValType: codeStr = SR.GenericConstraintNotSatisfiedValType; break; case ErrorCode.ERR_CantInferMethTypeArgs: codeStr = SR.CantInferMethTypeArgs; break; case ErrorCode.ERR_RefConstraintNotSatisfied: codeStr = SR.RefConstraintNotSatisfied; break; case ErrorCode.ERR_ValConstraintNotSatisfied: codeStr = SR.ValConstraintNotSatisfied; break; case ErrorCode.ERR_AmbigUDConv: codeStr = SR.AmbigUDConv; break; case ErrorCode.ERR_BindToBogus: codeStr = SR.BindToBogus; break; case ErrorCode.ERR_CantCallSpecialMethod: codeStr = SR.CantCallSpecialMethod; break; case ErrorCode.ERR_ConvertToStaticClass: codeStr = SR.ConvertToStaticClass; break; case ErrorCode.ERR_IncrementLvalueExpected: codeStr = SR.IncrementLvalueExpected; break; case ErrorCode.ERR_BadArgCount: codeStr = SR.BadArgCount; break; case ErrorCode.ERR_BadArgTypes: codeStr = SR.BadArgTypes; break; case ErrorCode.ERR_BadProtectedAccess: codeStr = SR.BadProtectedAccess; break; case ErrorCode.ERR_BindToBogusProp2: codeStr = SR.BindToBogusProp2; break; case ErrorCode.ERR_BindToBogusProp1: codeStr = SR.BindToBogusProp1; break; case ErrorCode.ERR_BadDelArgCount: codeStr = SR.BadDelArgCount; break; case ErrorCode.ERR_BadDelArgTypes: codeStr = SR.BadDelArgTypes; break; case ErrorCode.ERR_BadCtorArgCount: codeStr = SR.BadCtorArgCount; break; case ErrorCode.ERR_NonInvocableMemberCalled: codeStr = SR.NonInvocableMemberCalled; break; case ErrorCode.ERR_BadNamedArgument: codeStr = SR.BadNamedArgument; break; case ErrorCode.ERR_BadNamedArgumentForDelegateInvoke: codeStr = SR.BadNamedArgumentForDelegateInvoke; break; case ErrorCode.ERR_DuplicateNamedArgument: codeStr = SR.DuplicateNamedArgument; break; case ErrorCode.ERR_NamedArgumentUsedInPositional: codeStr = SR.NamedArgumentUsedInPositional; break; case ErrorCode.ERR_BadNonTrailingNamedArgument: codeStr = SR.BadNonTrailingNamedArgument; break; default: // means missing resources match the code entry Debug.Assert(false, "Missing resources for the error " + code.ToString()); codeStr = null; break; } return codeStr; } public static string GetMessage(MessageID id) { return id.ToString(); } } }
// 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; using System.Runtime.InteropServices; using System.Security.Cryptography; namespace System.Security { public sealed partial class SecureString { internal SecureString(SecureString str) { Debug.Assert(str != null, "Expected non-null SecureString"); Debug.Assert(str._buffer != null, "Expected other SecureString's buffer to be non-null"); Debug.Assert(str._encrypted, "Expected to be used only on encrypted SecureStrings"); AllocateBuffer(str._buffer.Length); SafeBSTRHandle.Copy(str._buffer, _buffer, str._buffer.Length * sizeof(char)); _decryptedLength = str._decryptedLength; _encrypted = str._encrypted; } private unsafe void InitializeSecureString(char* value, int length) { Debug.Assert(length >= 0, $"Expected non-negative length, got {length}"); AllocateBuffer((uint)length); _decryptedLength = length; byte* bufferPtr = null; try { _buffer.AcquirePointer(ref bufferPtr); Buffer.MemoryCopy((byte*)value, bufferPtr, (long)_buffer.ByteLength, length * sizeof(char)); } finally { if (bufferPtr != null) { _buffer.ReleasePointer(); } } ProtectMemory(); } private void AppendCharCore(char c) { UnprotectMemory(); try { EnsureCapacity(_decryptedLength + 1); _buffer.Write<char>((uint)_decryptedLength * sizeof(char), c); _decryptedLength++; } finally { ProtectMemory(); } } private void ClearCore() { _decryptedLength = 0; _buffer.ClearBuffer(); } private void DisposeCore() { if (_buffer != null) { _buffer.Dispose(); _buffer = null; } } private unsafe void InsertAtCore(int index, char c) { byte* bufferPtr = null; UnprotectMemory(); try { EnsureCapacity(_decryptedLength + 1); _buffer.AcquirePointer(ref bufferPtr); char* pBuffer = (char*)bufferPtr; for (int i = _decryptedLength; i > index; i--) { pBuffer[i] = pBuffer[i - 1]; } pBuffer[index] = c; ++_decryptedLength; } finally { ProtectMemory(); if (bufferPtr != null) { _buffer.ReleasePointer(); } } } private unsafe void RemoveAtCore(int index) { byte* bufferPtr = null; UnprotectMemory(); try { _buffer.AcquirePointer(ref bufferPtr); char* pBuffer = (char*)bufferPtr; for (int i = index; i < _decryptedLength - 1; i++) { pBuffer[i] = pBuffer[i + 1]; } pBuffer[--_decryptedLength] = (char)0; } finally { ProtectMemory(); if (bufferPtr != null) { _buffer.ReleasePointer(); } } } private void SetAtCore(int index, char c) { UnprotectMemory(); try { _buffer.Write<char>((uint)index * sizeof(char), c); } finally { ProtectMemory(); } } internal unsafe IntPtr MarshalToBSTRCore() { int length = _decryptedLength; IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; byte* bufferPtr = null; UnprotectMemory(); try { _buffer.AcquirePointer(ref bufferPtr); int resultByteLength = (length + 1) * sizeof(char); ptr = PInvokeMarshal.AllocBSTR(length); Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char)); result = ptr; } finally { ProtectMemory(); // If we failed for any reason, free the new buffer if (result == IntPtr.Zero && ptr != IntPtr.Zero) { RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char))); PInvokeMarshal.FreeBSTR(ptr); } if (bufferPtr != null) { _buffer.ReleasePointer(); } } return result; } internal unsafe IntPtr MarshalToStringCore(bool globalAlloc, bool unicode) { int length = _decryptedLength; IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; byte* bufferPtr = null; UnprotectMemory(); try { _buffer.AcquirePointer(ref bufferPtr); if (unicode) { int resultByteLength = (length + 1) * sizeof(char); ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength); Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char)); *(length + (char*)ptr) = '\0'; } else { uint defaultChar = '?'; int resultByteLength = 1 + Interop.Kernel32.WideCharToMultiByte( Interop.Kernel32.CP_ACP, Interop.Kernel32.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, null, 0, (IntPtr)(&defaultChar), IntPtr.Zero); ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength); Interop.Kernel32.WideCharToMultiByte( Interop.Kernel32.CP_ACP, Interop.Kernel32.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, (byte*)ptr, resultByteLength - 1, (IntPtr)(&defaultChar), IntPtr.Zero); *(resultByteLength - 1 + (byte*)ptr) = 0; } result = ptr; } finally { ProtectMemory(); // If we failed for any reason, free the new buffer if (result == IntPtr.Zero && ptr != IntPtr.Zero) { RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char))); MarshalFree(ptr, globalAlloc); } if (bufferPtr != null) { _buffer.ReleasePointer(); } } return result; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private const int BlockSize = (int)Interop.Crypt32.CRYPTPROTECTMEMORY_BLOCK_SIZE / sizeof(char); private SafeBSTRHandle _buffer; private bool _encrypted; private void AllocateBuffer(uint size) { _buffer = SafeBSTRHandle.Allocate(GetAlignedSize(size)); } private static uint GetAlignedSize(uint size) => size == 0 || size % BlockSize != 0 ? BlockSize + ((size / BlockSize) * BlockSize) : size; private void EnsureCapacity(int capacity) { if (capacity > MaxLength) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity); } if (((uint)capacity * sizeof(char)) <= _buffer.ByteLength) { return; } var oldBuffer = _buffer; SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(GetAlignedSize((uint)capacity)); SafeBSTRHandle.Copy(oldBuffer, newBuffer, (uint)_decryptedLength * sizeof(char)); _buffer = newBuffer; oldBuffer.Dispose(); } private void ProtectMemory() { Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!"); if (_decryptedLength != 0 && !_encrypted && !Interop.Crypt32.CryptProtectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } _encrypted = true; } private void UnprotectMemory() { Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!"); if (_decryptedLength != 0 && _encrypted && !Interop.Crypt32.CryptUnprotectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } _encrypted = false; } } }
/* * Copyright (c) 2016 Tenebrous * * 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. * * Latest version: https://bitbucket.org/Tenebrous/unityeditorenhancements/wiki/Home */ using Tenebrous.EditorEnhancements; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; public class TeneEnhPreviewWindow : EditorWindow { private static TeneEnhPreviewWindow _window; private Object _asset; private Texture2D _tex; private double _timeStart; private bool _noPreview; private string _info; private bool _hasAlpha; private bool _anchoredToRight; public static void Update( Rect pAnchorTo, Vector2 pMousePosition, string pGUID = null, Object pAsset = null ) { if( ( pGUID == null && pAsset == null ) || !CanShowPreviewFor(pGUID:pGUID, pAsset:pAsset) ) { if( _window != null ) { _window.Close(); _window = null; } return; } if( _window == null ) _window = EditorWindow.GetWindow<TeneEnhPreviewWindow>( true ); _window.SetPosition( pAnchorTo, pMousePosition ); _window.SetPreview( pGUID: pGUID, pAsset: pAsset ); } static void Resolve( ref string pGUID, ref string pPath, ref Object pAsset ) { if( pGUID != null ) pPath = AssetDatabase.GUIDToAssetPath( pGUID ); if( pPath != null ) pAsset = AssetDatabase.LoadAssetAtPath( pPath, typeof( Object ) ); if( pAsset is MeshFilter ) pAsset = ( (MeshFilter)pAsset ).sharedMesh; else if( pAsset is AudioSource ) pAsset = ( (AudioSource)pAsset ).clip; else if( pAsset is GameObject ) { GameObject pBaseAsset = PrefabUtility.GetCorrespondingObjectFromSource(pAsset) as GameObject; if( pBaseAsset != null ) pAsset = pBaseAsset; } } static bool CanShowPreviewFor( string pGUID = null, string pPath = null, Object pAsset = null ) { Resolve( ref pGUID, ref pPath, ref pAsset ); // include specific things if( pAsset is Camera ) return (true); if( pAsset is GameObject ) return ((GameObject) pAsset).HasAnyRenderers(); // exclude specific things return( pAsset != null && !( pAsset is MonoScript ) && !( pAsset is TextAsset ) && !( pAsset is MonoBehaviour ) && !( pAsset is Behaviour ) && !( pAsset is Collider ) && !( pAsset is Component ) && pAsset.GetType().ToString() != "UnityEngine.Object" ); } private void SetPosition( Rect pWindow, Vector2 pMouse ) { Rect newPos = new Rect( pWindow.x - 210, pMouse.y - 90, 200, 200 ); _anchoredToRight = false; if( newPos.x < 0 ) { newPos.x = pWindow.x + pWindow.width; _anchoredToRight = true; } newPos.y = Mathf.Clamp( newPos.y, 0, Screen.currentResolution.height - 250 ); position = newPos; } private void SetPreview( string pGUID = null, string pPath = null, Object pAsset = null ) { Resolve( ref pGUID, ref pPath, ref pAsset ); // string newTitle = pAsset.name + " (" + pAsset.GetType().ToString().Replace("UnityEngine.", "") + ")"; #if (UNITY_5 || UNITY_5_3_OR_NEWER) && !UNITY_5_0 titleContent = new GUIContent(newTitle); #else title = newTitle; #endif _asset = pAsset; _noPreview = false; _hasAlpha = false; _info = ""; if( pAsset == null ) return; if( _asset is Texture2D ) { _tex = (Texture2D)_asset; _hasAlpha = true; if( _anchoredToRight ) position = new Rect( position.x, position.y, position.width + 200, position.height ); else position = new Rect( position.x - 200, position.y, position.width + 200, position.height ); } else _tex = Common.GetAssetPreview( _asset ); _info += _asset.GetPreviewInfo();// +"\n" + _asset.GetType().ToString(); _timeStart = EditorApplication.timeSinceStartup; _window.Repaint(); if( EditorWindow.mouseOverWindow != null ) EditorWindow.mouseOverWindow.Focus(); } void Update() { if( _tex == null && _asset != null ) { _tex = Common.GetAssetPreview( _asset ); if( _tex != null ) Repaint(); else if( EditorApplication.timeSinceStartup - _timeStart > 3.0f ) { _noPreview = true; Repaint(); } } } void OnGUI() { Rect pos = position; pos.x = 0; pos.y = 0; if( _tex != null ) ShowTexture( pos ); if( _asset is Camera ) ShowCamera(pos, (Camera)_asset); else if( _asset is MonoBehaviour || _asset is Component ) ShowMonoBehaviour( pos ); pos.y = pos.height - EditorStyles.boldLabel.CalcHeight( new GUIContent( _info ), pos.width ); pos.height -= pos.y; GUIStyle s = new GUIStyle( EditorStyles.boldLabel ); s.normal.textColor = Color.white; GUI.color = Color.white; EditorGUI.DropShadowLabel( pos, _info, s ); } void ShowCamera( Rect pPos, Camera pCamera ) { Rect oldViewport = pCamera.rect; Handles.DrawCamera(pPos, pCamera); pCamera.rect = oldViewport; } void ShowMonoBehaviour(Rect pPos) { //MonoScript ms = MonoScript.FromMonoBehaviour( _asset as MonoBehaviour ); //GUI.Label(pPos,ms.GetPreviewInfo()); } void ShowTexture(Rect pPos) { if( _tex == null ) { if( _noPreview ) GUI.Label( pPos, "No preview\n\n" + _info ); else GUI.Label( pPos, "Loading...\n\n" + _info ); } else { GUI.color = Color.white; if( _hasAlpha ) { Rect half = pPos; half.width /= 2; EditorGUI.DrawTextureAlpha( half, _tex ); half.x += half.width; EditorGUI.DrawPreviewTexture( half, _tex ); } else { //GUI.DrawTexture(pPos, EditorGUIUtility.whiteTexture); GUI.DrawTexture(pPos, _tex, ScaleMode.StretchToFill, true); } } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.Utilclass.DN.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.Collections; namespace Novell.Directory.Ldap.Utilclass { /// <summary> A DN encapsulates a Distinguished Name (an ldap name with context). A DN /// does not need to be fully distinguished, or extend to the Root of a /// directory. It provides methods to get information about the DN and to /// manipulate the DN. /// /// The following are examples of valid DN: /// <ul> /// <li>cn=admin,ou=marketing,o=corporation</li> /// <li>cn=admin,ou=marketing</li> /// <li>2.5.4.3=admin,ou=marketing</li> /// <li>oid.2.5.4.3=admin,ou=marketing</li> /// </ul> /// /// Note: Multivalued attributes are all considered to be one /// component and are represented in one RDN (see RDN) /// /// /// </summary> /// <seealso cref="RDN"> /// </seealso> public class DN : object { private void InitBlock() { rdnList = new ArrayList(); } /// <summary> Retrieves a list of RDN Objects, or individual names of the DN</summary> /// <returns> list of RDNs /// </returns> virtual public ArrayList RDNs { get { int size = rdnList.Count; ArrayList v = new ArrayList(size); for (int i = 0; i < size; i++) { v.Add(rdnList[i]); } return v; } } /// <summary> Returns the Parent of this DN</summary> /// <returns> Parent DN /// </returns> virtual public DN Parent { get { DN parent = new DN(); parent.rdnList = (ArrayList)rdnList.Clone(); if (parent.rdnList.Count >= 1) parent.rdnList.Remove(rdnList[0]); //remove first object return parent; } } //parser state identifiers. private const int LOOK_FOR_RDN_ATTR_TYPE = 1; private const int ALPHA_ATTR_TYPE = 2; private const int OID_ATTR_TYPE = 3; private const int LOOK_FOR_RDN_VALUE = 4; private const int QUOTED_RDN_VALUE = 5; private const int HEX_RDN_VALUE = 6; private const int UNQUOTED_RDN_VALUE = 7; /* State transition table: Parsing starts in state 1. State COMMA DIGIT "Oid." ALPHA EQUAL QUOTE SHARP HEX -------------------------------------------------------------------- 1 Err 3 3 2 Err Err Err Err 2 Err Err Err 2 4 Err Err Err 3 Err 3 Err Err 4 Err Err Err 4 Err 7 Err 7 Err 5 6 7 5 1 5 Err 5 Err 1 Err 7 6 1 6 Err Err Err Err Err 6 7 1 7 Err 7 Err Err Err 7 */ private ArrayList rdnList; public DN() { InitBlock(); return; } /// <summary> Constructs a new DN based on the specified string representation of a /// distinguished name. The syntax of the DN must conform to that specified /// in RFC 2253. /// /// </summary> /// <param name="dnString">a string representation of the distinguished name /// </param> /// <exception> IllegalArgumentException if the the value of the dnString /// parameter does not adhere to the syntax described in /// RFC 2253 /// </exception> public DN(string dnString) { InitBlock(); /* the empty string is a valid DN */ if (dnString.Length == 0) return; char currChar; char nextChar; int currIndex; char[] tokenBuf = new char[dnString.Length]; int tokenIndex; int lastIndex; int valueStart; int state; int trailingSpaceCount = 0; string attrType = ""; string attrValue = ""; string rawValue = ""; int hexDigitCount = 0; RDN currRDN = new RDN(); //indicates whether an OID number has a first digit of ZERO bool firstDigitZero = false; tokenIndex = 0; currIndex = 0; valueStart = 0; state = LOOK_FOR_RDN_ATTR_TYPE; lastIndex = dnString.Length - 1; while (currIndex <= lastIndex) { currChar = dnString[currIndex]; switch (state) { case LOOK_FOR_RDN_ATTR_TYPE: while (currChar == ' ' && (currIndex < lastIndex)) currChar = dnString[++currIndex]; if (isAlpha(currChar)) { if (dnString.Substring(currIndex).StartsWith("oid.") || dnString.Substring(currIndex).StartsWith("OID.")) { //form is "oid.###.##.###... or OID.###.##.###... currIndex += 4; //skip oid. prefix and get to actual oid if (currIndex > lastIndex) throw new ArgumentException(dnString); currChar = dnString[currIndex]; if (isDigit(currChar)) { tokenBuf[tokenIndex++] = currChar; state = OID_ATTR_TYPE; } else throw new ArgumentException(dnString); } else { tokenBuf[tokenIndex++] = currChar; state = ALPHA_ATTR_TYPE; } } else if (isDigit(currChar)) { --currIndex; state = OID_ATTR_TYPE; } else if (System.Globalization.CharUnicodeInfo.GetUnicodeCategory(currChar) != System.Globalization.UnicodeCategory.SpaceSeparator) throw new ArgumentException(dnString); break; case ALPHA_ATTR_TYPE: if (isAlpha(currChar) || isDigit(currChar) || (currChar == '-')) tokenBuf[tokenIndex++] = currChar; else { //skip any spaces while ((currChar == ' ') && (currIndex < lastIndex)) currChar = dnString[++currIndex]; if (currChar == '=') { attrType = new string(tokenBuf, 0, tokenIndex); tokenIndex = 0; state = LOOK_FOR_RDN_VALUE; } else throw new ArgumentException(dnString); } break; case OID_ATTR_TYPE: if (!isDigit(currChar)) throw new ArgumentException(dnString); firstDigitZero = (currChar == '0'); tokenBuf[tokenIndex++] = currChar; currChar = dnString[++currIndex]; if ((isDigit(currChar) && firstDigitZero) || (currChar == '.' && firstDigitZero)) { throw new ArgumentException(dnString); } //consume all numbers. while (isDigit(currChar) && (currIndex < lastIndex)) { tokenBuf[tokenIndex++] = currChar; currChar = dnString[++currIndex]; } if (currChar == '.') { tokenBuf[tokenIndex++] = currChar; //The state remains at OID_ATTR_TYPE } else { //skip any spaces while (currChar == ' ' && (currIndex < lastIndex)) currChar = dnString[++currIndex]; if (currChar == '=') { attrType = new string(tokenBuf, 0, tokenIndex); tokenIndex = 0; state = LOOK_FOR_RDN_VALUE; } else throw new ArgumentException(dnString); } break; case LOOK_FOR_RDN_VALUE: while (currChar == ' ') { if (currIndex < lastIndex) currChar = dnString[++currIndex]; else throw new ArgumentException(dnString); } if (currChar == '"') { state = QUOTED_RDN_VALUE; valueStart = currIndex; } else if (currChar == '#') { hexDigitCount = 0; tokenBuf[tokenIndex++] = currChar; valueStart = currIndex; state = HEX_RDN_VALUE; } else { valueStart = currIndex; //check this character again in the UNQUOTED_RDN_VALUE state currIndex--; state = UNQUOTED_RDN_VALUE; } break; case UNQUOTED_RDN_VALUE: if (currChar == '\\') { if (!(currIndex < lastIndex)) throw new ArgumentException(dnString); currChar = dnString[++currIndex]; if (isHexDigit(currChar)) { if (!(currIndex < lastIndex)) throw new ArgumentException(dnString); nextChar = dnString[++currIndex]; if (isHexDigit(nextChar)) { tokenBuf[tokenIndex++] = hexToChar(currChar, nextChar); trailingSpaceCount = 0; } else throw new ArgumentException(dnString); } else if (needsEscape(currChar) || currChar == '#' || currChar == '=' || currChar == ' ') { tokenBuf[tokenIndex++] = currChar; trailingSpaceCount = 0; } else throw new ArgumentException(dnString); } else if (currChar == ' ') { trailingSpaceCount++; tokenBuf[tokenIndex++] = currChar; } else if ((currChar == ',') || (currChar == ';') || (currChar == '+')) { attrValue = new string(tokenBuf, 0, tokenIndex - trailingSpaceCount); rawValue = dnString.Substring(valueStart, (currIndex - trailingSpaceCount) - (valueStart)); currRDN.add(attrType, attrValue, rawValue); if (currChar != '+') { rdnList.Add(currRDN); currRDN = new RDN(); } trailingSpaceCount = 0; tokenIndex = 0; state = LOOK_FOR_RDN_ATTR_TYPE; } else if (needsEscape(currChar)) { throw new ArgumentException(dnString); } else { trailingSpaceCount = 0; tokenBuf[tokenIndex++] = currChar; } break; //end UNQUOTED RDN VALUE case QUOTED_RDN_VALUE: if (currChar == '"') { rawValue = dnString.Substring(valueStart, (currIndex + 1) - (valueStart)); if (currIndex < lastIndex) currChar = dnString[++currIndex]; //skip any spaces while ((currChar == ' ') && (currIndex < lastIndex)) currChar = dnString[++currIndex]; if ((currChar == ',') || (currChar == ';') || (currChar == '+') || (currIndex == lastIndex)) { attrValue = new string(tokenBuf, 0, tokenIndex); currRDN.add(attrType, attrValue, rawValue); if (currChar != '+') { rdnList.Add(currRDN); currRDN = new RDN(); } trailingSpaceCount = 0; tokenIndex = 0; state = LOOK_FOR_RDN_ATTR_TYPE; } else throw new ArgumentException(dnString); } else if (currChar == '\\') { currChar = dnString[++currIndex]; if (isHexDigit(currChar)) { nextChar = dnString[++currIndex]; if (isHexDigit(nextChar)) { tokenBuf[tokenIndex++] = hexToChar(currChar, nextChar); trailingSpaceCount = 0; } else throw new ArgumentException(dnString); } else if (needsEscape(currChar) || currChar == '#' || currChar == '=' || currChar == ' ') { tokenBuf[tokenIndex++] = currChar; trailingSpaceCount = 0; } else throw new ArgumentException(dnString); } else tokenBuf[tokenIndex++] = currChar; break; //end QUOTED RDN VALUE case HEX_RDN_VALUE: if ((!isHexDigit(currChar)) || (currIndex > lastIndex)) { //check for odd number of hex digits if ((hexDigitCount % 2) != 0 || hexDigitCount == 0) throw new ArgumentException(dnString); else { rawValue = dnString.Substring(valueStart, (currIndex) - (valueStart)); //skip any spaces while ((currChar == ' ') && (currIndex < lastIndex)) currChar = dnString[++currIndex]; if ((currChar == ',') || (currChar == ';') || (currChar == '+') || (currIndex == lastIndex)) { attrValue = new string(tokenBuf, 0, tokenIndex); //added by cameron currRDN.add(attrType, attrValue, rawValue); if (currChar != '+') { rdnList.Add(currRDN); currRDN = new RDN(); } tokenIndex = 0; state = LOOK_FOR_RDN_ATTR_TYPE; } else { throw new ArgumentException(dnString); } } } else { tokenBuf[tokenIndex++] = currChar; hexDigitCount++; } break; //end HEX RDN VALUE } //end switch currIndex++; } //end while //check ending state if (state == UNQUOTED_RDN_VALUE || (state == HEX_RDN_VALUE && (hexDigitCount % 2) == 0) && hexDigitCount != 0) { attrValue = new string(tokenBuf, 0, tokenIndex - trailingSpaceCount); rawValue = dnString.Substring(valueStart, (currIndex - trailingSpaceCount) - (valueStart)); currRDN.add(attrType, attrValue, rawValue); rdnList.Add(currRDN); } else if (state == LOOK_FOR_RDN_VALUE) { //empty value is valid attrValue = ""; rawValue = dnString.Substring(valueStart); currRDN.add(attrType, attrValue, rawValue); rdnList.Add(currRDN); } else { throw new ArgumentException(dnString); } } //end DN constructor (string dn) /// <summary> Checks a character to see if it is an ascii alphabetic character in /// ranges 65-90 or 97-122. /// /// </summary> /// <param name="ch">the character to be tested. /// </param> /// <returns> <code>true</code> if the character is an ascii alphabetic /// character /// </returns> private bool isAlpha(char ch) { if (((ch < 91) && (ch > 64)) || ((ch < 123) && (ch > 96))) //ASCII A-Z return true; return false; } /// <summary> Checks a character to see if it is an ascii digit (0-9) character in /// the ascii value range 48-57. /// /// </summary> /// <param name="ch">the character to be tested. /// </param> /// <returns> <code>true</code> if the character is an ascii alphabetic /// character /// </returns> private bool isDigit(char ch) { if ((ch < 58) && (ch > 47)) //ASCII 0-9 return true; return false; } /// <summary> Checks a character to see if it is valid hex digit 0-9, a-f, or /// A-F (ASCII value ranges 48-47, 65-70, 97-102). /// /// </summary> /// <param name="ch">the character to be tested. /// </param> /// <returns> <code>true</code> if the character is a valid hex digit /// </returns> private static bool isHexDigit(char ch) { if (((ch < 58) && (ch > 47)) || ((ch < 71) && (ch > 64)) || ((ch < 103) && (ch > 96))) //ASCII A-F return true; return false; } /// <summary> Checks a character to see if it must always be escaped in the /// string representation of a DN. We must tests for space, sharp, and /// equals individually. /// /// </summary> /// <param name="ch">the character to be tested. /// </param> /// <returns> <code>true</code> if the character needs to be escaped in at /// least some instances. /// </returns> private bool needsEscape(char ch) { if ((ch == ',') || (ch == '+') || (ch == '\"') || (ch == ';') || (ch == '<') || (ch == '>') || (ch == '\\')) return true; return false; } /// <summary> Converts two valid hex digit characters that form the string /// representation of an ascii character value to the actual ascii /// character. /// /// </summary> /// <param name="hex1">the hex digit for the high order byte. /// </param> /// <param name="hex0">the hex digit for the low order byte. /// </param> /// <returns> the character whose value is represented by the parameters. /// </returns> private static char hexToChar(char hex1, char hex0) { int result; if ((hex1 < 58) && (hex1 > 47)) //ASCII 0-9 result = (hex1 - 48) * 16; else if ((hex1 < 71) && (hex1 > 64)) //ASCII a-f result = (hex1 - 55) * 16; else if ((hex1 < 103) && (hex1 > 96)) //ASCII A-F result = (hex1 - 87) * 16; else throw new ArgumentException("Not hex digit"); if ((hex0 < 58) && (hex0 > 47)) //ASCII 0-9 result += (hex0 - 48); else if ((hex0 < 71) && (hex0 > 64)) //ASCII a-f result += (hex0 - 55); else if ((hex0 < 103) && (hex0 > 96)) //ASCII A-F result += (hex0 - 87); else throw new ArgumentException("Not hex digit"); return (char)result; } /// <summary> Creates and returns a string that represents this DN. The string /// follows RFC 2253, which describes String representation of DN's and /// RDN's /// /// </summary> /// <returns> A DN string. /// </returns> public override string ToString() { int length = rdnList.Count; string dn = ""; if (length < 1) return null; dn = rdnList[0].ToString(); for (int i = 1; i < length; i++) { dn += ("," + rdnList[i].ToString()); } return dn; } /// <summary> Compares this DN to the specified DN to determine if they are equal. /// /// </summary> /// <param name="toDN">the DN to compare to /// </param> /// <returns> <code>true</code> if the DNs are equal; otherwise /// <code>false</code> /// </returns> public ArrayList getrdnList() { return rdnList; } public override bool Equals(object toDN) { return Equals((DN)toDN); } public bool Equals(DN toDN) { ArrayList aList = toDN.getrdnList(); int length = aList.Count; if (rdnList.Count != length) return false; for (int i = 0; i < length; i++) { if (!((RDN)rdnList[i]).equals((RDN)toDN.getrdnList()[i])) return false; } return true; } /// <summary> return a string array of the individual RDNs contained in the DN /// /// </summary> /// <param name="noTypes"> If true, returns only the values of the /// components, and not the names, e.g. "Babs /// Jensen", "Accounting", "Acme", "us" - instead of /// "cn=Babs Jensen", "ou=Accounting", "o=Acme", and /// "c=us". /// </param> /// <returns> <code>String[]</code> containing the rdns in the DN with /// the leftmost rdn in the first element of the array /// /// </returns> public virtual string[] explodeDN(bool noTypes) { int length = rdnList.Count; string[] rdns = new string[length]; for (int i = 0; i < length; i++) rdns[i] = ((RDN)rdnList[i]).ToString(noTypes); return rdns; } /// <summary> Retrieves the count of RDNs, or individule names, in the Distinguished name</summary> /// <returns> the count of RDN /// </returns> public virtual int countRDNs() { return rdnList.Count; } /// <summary>Determines if this DN is <I>contained</I> by the DN passed in. For /// example: "cn=admin, ou=marketing, o=corporation" is contained by /// "o=corporation", "ou=marketing, o=corporation", and "ou=marketing" /// but <B>not</B> by "cn=admin" or "cn=admin,ou=marketing,o=corporation" /// Note: For users of Netscape's SDK this method is comparable to contains /// /// </summary> /// <param name="containerDN">of a container /// </param> /// <returns> true if containerDN contains this DN /// </returns> public virtual bool isDescendantOf(DN containerDN) { int i = containerDN.rdnList.Count - 1; //index to an RDN of the ContainerDN int j = rdnList.Count - 1; //index to an RDN of the ContainedDN //Search from the end of the DN for an RDN that matches the end RDN of //containerDN. while (!((RDN)rdnList[j]).equals((RDN)containerDN.rdnList[i])) { j--; if (j <= 0) return false; //if the end RDN of containerDN does not have any equal //RDN in rdnList, then containerDN does not contain this DN } i--; //avoid a redundant compare j--; //step backwards to verify that all RDNs in containerDN exist in this DN for (; i >= 0 && j >= 0; i--, j--) { if (!((RDN)rdnList[j]).equals((RDN)containerDN.rdnList[i])) return false; } if (j == 0 && i == 0) //the DNs are identical and thus not contained return false; return true; } /// <summary> Adds the RDN to the beginning of the current DN.</summary> /// <param name="rdn">an RDN to be added /// </param> public virtual void addRDN(RDN rdn) { rdnList.Insert(0, rdn); } /// <summary> Adds the RDN to the beginning of the current DN.</summary> /// <param name="rdn">an RDN to be added /// </param> public virtual void addRDNToFront(RDN rdn) { rdnList.Insert(0, rdn); } /// <summary> Adds the RDN to the end of the current DN</summary> /// <param name="rdn">an RDN to be added /// </param> public virtual void addRDNToBack(RDN rdn) { rdnList.Add(rdn); } } //end class DN }
using System; using EncompassRest.Loans.Enums; namespace EncompassRest.Loans { /// <summary> /// LoanEstimate1 /// </summary> public sealed partial class LoanEstimate1 : DirtyExtensibleObject, IIdentifiable { private DirtyValue<StringEnumValue<TermType>>? _adjustsTermType; private DirtyValue<StringEnumValue<MonthOrYear>>? _balloonPaymentDueInTermLabel; private DirtyValue<string?>? _changedCircumstanceComments; private DirtyValue<DateTime?>? _closingCostEstimateExpirationDate; private DirtyValue<string?>? _closingCostEstimateExpirationDateUI; private DirtyValue<string?>? _closingCostEstimateExpirationTime; private DirtyValue<string?>? _closingCostEstimateExpirationTimeUI; private DirtyValue<string?>? _closingCostEstimateExpirationTimeZone; private DirtyValue<string?>? _closingCostEstimateExpirationTimeZoneUI; private DirtyValue<StringEnumValue<Conversion>>? _conversionBegin; private DirtyValue<StringEnumValue<Conversion>>? _conversionEnd; private DirtyValue<string?>? _disclosureBy; private DirtyValue<DateTime?>? _disclosureClosingCostExpDate; private DirtyValue<string?>? _disclosureClosingCostExpTime; private DirtyValue<string?>? _disclosureClosingCostExpTimeZone; private DirtyValue<string?>? _disclosureComments; private DirtyValue<DateTime?>? _disclosureLastSentDate; private DirtyValue<DateTime?>? _disclosureReceivedDate; private DirtyValue<string?>? _disclosureSentMethod; private DirtyValue<decimal?>? _estimatedTaxesInsuranceAssessments; private DirtyValue<string?>? _estimatedTaxesInsuranceAssessmentsUI; private DirtyValue<decimal?>? _highestMonthlyPI; private DirtyValue<string?>? _id; private DirtyValue<string?>? _inEscrowHomeownerInsurance; private DirtyValue<string?>? _inEscrowOther; private DirtyValue<string?>? _inEscrowPropertyTaxes; private DirtyValue<decimal?>? _initialMonthlyPaymentFor10000Loan; private DirtyValue<decimal?>? _initialMonthlyPaymentFor60000Loan; private DirtyValue<StringEnumValue<MonthOrYear>>? _interestRateAdjTermLabel; private DirtyValue<string?>? _interestRateAdjustsEveryYears; private DirtyValue<int?>? _interestRateAdjustsInYear; private DirtyValue<StringEnumValue<MonthOrYear>>? _interestRateAdjustsStartingInType; private DirtyValue<int?>? _interestRateAfterAdjustment; private DirtyValue<StringEnumValue<CanGoOrGoes>>? _interestRateCanGoGoes; private DirtyValue<DateTime?>? _lEDateIssued; private DirtyValue<StringEnumValue<CanGoOrGoes>>? _loanAmountCanGoGoes; private DirtyValue<StringEnumValue<CanIncreaseOrIncreases>>? _loanAmountCanIncreaseOrIncreases; private DirtyValue<string?>? _loanProduct; private DirtyValue<StringEnumValue<LoanEstimate1LoanPurpose>>? _loanPurpose; private DirtyValue<int?>? _loanTermMonths; private DirtyValue<int?>? _loanTermYears; private DirtyValue<decimal?>? _maximumMonthlyPaymentFor10000Loan; private DirtyValue<int?>? _maximumPaymentMonth; private DirtyValue<StringEnumValue<MonthOrYear>>? _monthlyPIAdjustedInDateType; private DirtyValue<string?>? _monthlyPIAdjustsEveryYears; private DirtyValue<int?>? _monthlyPIAdjustsInYear; private DirtyValue<StringEnumValue<MonthOrYear>>? _monthlyPIAdjustsStartingInType; private DirtyValue<StringEnumValue<TermType>>? _monthlyPIAdjustsTermType; private DirtyValue<int?>? _monthlyPIAfterAdjustment; private DirtyValue<StringEnumValue<CanGoOrGoes>>? _monthlyPICanGoGoes; private DirtyValue<StringEnumValue<MonthOrYear>>? _monthlyPIInterestOnlyDateType; private DirtyValue<int?>? _monthlyPIInterestOnlyUntilYear; private DirtyValue<int?>? _pPC1EstimatedEscrowAmount; private DirtyValue<string?>? _pPC1EstimatedEscrowAmountUI; private DirtyValue<bool?>? _pPC1InterestOnly; private DirtyValue<decimal?>? _pPC1MaximumMonthlyPayment; private DirtyValue<string?>? _pPC1MaximumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC1MaximumPIPayment; private DirtyValue<string?>? _pPC1MaximumPIPaymentUI; private DirtyValue<int?>? _pPC1MIAmount; private DirtyValue<string?>? _pPC1MIAmountUI; private DirtyValue<int?>? _pPC1MinimumMonthlyPayment; private DirtyValue<string?>? _pPC1MinimumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC1MinimumPIPayment; private DirtyValue<string?>? _pPC1MinimumPIPaymentUI; private DirtyValue<int?>? _pPC1Year; private DirtyValue<int?>? _pPC2EstimatedEscrowAmount; private DirtyValue<string?>? _pPC2EstimatedEscrowAmountUI; private DirtyValue<bool?>? _pPC2InterestOnly; private DirtyValue<decimal?>? _pPC2MaximumMonthlyPayment; private DirtyValue<string?>? _pPC2MaximumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC2MaximumPIPayment; private DirtyValue<string?>? _pPC2MaximumPIPaymentUI; private DirtyValue<int?>? _pPC2MIAmount; private DirtyValue<string?>? _pPC2MIAmountUI; private DirtyValue<int?>? _pPC2MinimumMonthlyPayment; private DirtyValue<string?>? _pPC2MinimumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC2MinimumPIPayment; private DirtyValue<string?>? _pPC2MinimumPIPaymentUI; private DirtyValue<int?>? _pPC2YearFrom; private DirtyValue<int?>? _pPC2YearTo; private DirtyValue<int?>? _pPC3EstimatedEscrowAmount; private DirtyValue<string?>? _pPC3EstimatedEscrowAmountUI; private DirtyValue<bool?>? _pPC3InterestOnly; private DirtyValue<decimal?>? _pPC3MaximumMonthlyPayment; private DirtyValue<string?>? _pPC3MaximumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC3MaximumPIPayment; private DirtyValue<string?>? _pPC3MaximumPIPaymentUI; private DirtyValue<int?>? _pPC3MIAmount; private DirtyValue<string?>? _pPC3MIAmountUI; private DirtyValue<int?>? _pPC3MinimumMonthlyPayment; private DirtyValue<string?>? _pPC3MinimumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC3MinimumPIPayment; private DirtyValue<string?>? _pPC3MinimumPIPaymentUI; private DirtyValue<int?>? _pPC3YearFrom; private DirtyValue<int?>? _pPC3YearTo; private DirtyValue<int?>? _pPC4EstimatedEscrowAmount; private DirtyValue<string?>? _pPC4EstimatedEscrowAmountUI; private DirtyValue<bool?>? _pPC4InterestOnly; private DirtyValue<decimal?>? _pPC4MaximumMonthlyPayment; private DirtyValue<string?>? _pPC4MaximumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC4MaximumPIPayment; private DirtyValue<string?>? _pPC4MaximumPIPaymentUI; private DirtyValue<int?>? _pPC4MIAmount; private DirtyValue<string?>? _pPC4MIAmountUI; private DirtyValue<int?>? _pPC4MinimumMonthlyPayment; private DirtyValue<string?>? _pPC4MinimumMonthlyPaymentUI; private DirtyValue<decimal?>? _pPC4MinimumPIPayment; private DirtyValue<string?>? _pPC4MinimumPIPaymentUI; private DirtyValue<int?>? _pPC4YearFrom; private DirtyValue<int?>? _pPC4YearTo; private DirtyValue<bool?>? _pPEstimatedEscrowIndicator; private DirtyValue<int?>? _prepaymentPenaltyPayOffDuringYear; private DirtyValue<StringEnumValue<TermType>>? _prepaymentPenaltyPayOffInDateType; private DirtyValue<string?>? _prepaymentPenaltyPayOffInFirstYear; private DirtyValue<bool?>? _rangePaymentIndicatorC1; private DirtyValue<bool?>? _rangePaymentIndicatorC2; private DirtyValue<bool?>? _rangePaymentIndicatorC3; private DirtyValue<bool?>? _rangePaymentIndicatorC4; private DirtyValue<string?>? _rateLockExpirationTime; private DirtyValue<string?>? _rateLockExpirationTimeZone; private DirtyValue<string?>? _reasonChangedCircumstanceFlags; private DirtyValue<bool?>? _reasonDelayedSettlement; private DirtyValue<bool?>? _reasonEligibility; private DirtyValue<bool?>? _reasonExpiration; private DirtyValue<bool?>? _reasonInterestRate; private DirtyValue<bool?>? _reasonOther; private DirtyValue<string?>? _reasonOtherDescription; private DirtyValue<bool?>? _reasonRevisions; private DirtyValue<bool?>? _reasonSettlementCharges; private DirtyValue<decimal?>? _totalEstimatedCashClose; private DirtyValue<int?>? _yearsToRecast; /// <summary> /// Loan Estimate - Interest Rate - Adjusts Every Months/Year/Years [LE1.X14] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Month\"]")] public StringEnumValue<TermType> AdjustsTermType { get => _adjustsTermType; set => SetField(ref _adjustsTermType, value); } /// <summary> /// Balloon Payment Period [LE1.X98] /// </summary> public StringEnumValue<MonthOrYear> BalloonPaymentDueInTermLabel { get => _balloonPaymentDueInTermLabel; set => SetField(ref _balloonPaymentDueInTermLabel, value); } /// <summary> /// Comments [LE1.X86] /// </summary> public string? ChangedCircumstanceComments { get => _changedCircumstanceComments; set => SetField(ref _changedCircumstanceComments, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Date [LE1.X28] /// </summary> public DateTime? ClosingCostEstimateExpirationDate { get => _closingCostEstimateExpirationDate; set => SetField(ref _closingCostEstimateExpirationDate, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Date UI Value [LE1.XD28] /// </summary> public string? ClosingCostEstimateExpirationDateUI { get => _closingCostEstimateExpirationDateUI; set => SetField(ref _closingCostEstimateExpirationDateUI, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Time [LE1.X8] /// </summary> public string? ClosingCostEstimateExpirationTime { get => _closingCostEstimateExpirationTime; set => SetField(ref _closingCostEstimateExpirationTime, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Time UI Value [LE1.XD8] /// </summary> public string? ClosingCostEstimateExpirationTimeUI { get => _closingCostEstimateExpirationTimeUI; set => SetField(ref _closingCostEstimateExpirationTimeUI, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Time Zone [LE1.X9] /// </summary> public string? ClosingCostEstimateExpirationTimeZone { get => _closingCostEstimateExpirationTimeZone; set => SetField(ref _closingCostEstimateExpirationTimeZone, value); } /// <summary> /// Loan Estimate - Closing Costs Estimate Expiration Time Zone UI Value [LE1.XD9] /// </summary> public string? ClosingCostEstimateExpirationTimeZoneUI { get => _closingCostEstimateExpirationTimeZoneUI; set => SetField(ref _closingCostEstimateExpirationTimeZoneUI, value); } /// <summary> /// Conversion Begin Period [LE1.X96] /// </summary> public StringEnumValue<Conversion> ConversionBegin { get => _conversionBegin; set => SetField(ref _conversionBegin, value); } /// <summary> /// Conversion End Period [LE1.X97] /// </summary> public StringEnumValue<Conversion> ConversionEnd { get => _conversionEnd; set => SetField(ref _conversionEnd, value); } /// <summary> /// Loan Estimate - Disclosure By [LE1.X34] /// </summary> public string? DisclosureBy { get => _disclosureBy; set => SetField(ref _disclosureBy, value); } /// <summary> /// Loan Estimate - Disclosure Closing Cost Exp. Date [LE1.X36] /// </summary> public DateTime? DisclosureClosingCostExpDate { get => _disclosureClosingCostExpDate; set => SetField(ref _disclosureClosingCostExpDate, value); } /// <summary> /// Loan Estimate - Disclosure Expiration Time [LE1.X37] /// </summary> public string? DisclosureClosingCostExpTime { get => _disclosureClosingCostExpTime; set => SetField(ref _disclosureClosingCostExpTime, value); } /// <summary> /// Loan Estimate - Disclosure Expiration Time Zone [LE1.X38] /// </summary> public string? DisclosureClosingCostExpTimeZone { get => _disclosureClosingCostExpTimeZone; set => SetField(ref _disclosureClosingCostExpTimeZone, value); } /// <summary> /// Loan Estimate - Disclosure Comments [LE1.X40] /// </summary> public string? DisclosureComments { get => _disclosureComments; set => SetField(ref _disclosureComments, value); } /// <summary> /// Loan Estimate - Disclosure Last Sent Date [LE1.X33] /// </summary> public DateTime? DisclosureLastSentDate { get => _disclosureLastSentDate; set => SetField(ref _disclosureLastSentDate, value); } /// <summary> /// Loan Estimate - Disclosure Received Date [LE1.X39] /// </summary> public DateTime? DisclosureReceivedDate { get => _disclosureReceivedDate; set => SetField(ref _disclosureReceivedDate, value); } /// <summary> /// Loan Estimate - Disclosure Sent Method [LE1.X35] /// </summary> public string? DisclosureSentMethod { get => _disclosureSentMethod; set => SetField(ref _disclosureSentMethod, value); } /// <summary> /// Loan Estimate - Estimated Taxes, Insurance and Assessments [LE1.X29] /// </summary> public decimal? EstimatedTaxesInsuranceAssessments { get => _estimatedTaxesInsuranceAssessments; set => SetField(ref _estimatedTaxesInsuranceAssessments, value); } /// <summary> /// Loan Estimate - Estimated Taxes, Insurance and Assessments UI Value [LE1.XD29] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? EstimatedTaxesInsuranceAssessmentsUI { get => _estimatedTaxesInsuranceAssessmentsUI; set => SetField(ref _estimatedTaxesInsuranceAssessmentsUI, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest Will be Adjusted in Year [LE1.X24] /// </summary> public decimal? HighestMonthlyPI { get => _highestMonthlyPI; set => SetField(ref _highestMonthlyPI, value); } /// <summary> /// LoanEstimate1 Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// Loan Estimate - In Escrow Homeowner Insurance [LE1.X31] /// </summary> public string? InEscrowHomeownerInsurance { get => _inEscrowHomeownerInsurance; set => SetField(ref _inEscrowHomeownerInsurance, value); } /// <summary> /// Loan Estimate - In Escrow Other [LE1.X32] /// </summary> public string? InEscrowOther { get => _inEscrowOther; set => SetField(ref _inEscrowOther, value); } /// <summary> /// Loan Estimate - In Escrow Property Taxes [LE1.X30] /// </summary> public string? InEscrowPropertyTaxes { get => _inEscrowPropertyTaxes; set => SetField(ref _inEscrowPropertyTaxes, value); } /// <summary> /// The calculated initial monthly payment for a $10,000 loan [LE1.X92] /// </summary> public decimal? InitialMonthlyPaymentFor10000Loan { get => _initialMonthlyPaymentFor10000Loan; set => SetField(ref _initialMonthlyPaymentFor10000Loan, value); } /// <summary> /// The calculation initial monthly payment for a $60,000 loan [LE1.X95] /// </summary> public decimal? InitialMonthlyPaymentFor60000Loan { get => _initialMonthlyPaymentFor60000Loan; set => SetField(ref _initialMonthlyPaymentFor60000Loan, value); } /// <summary> /// Maximum Interest Period [LE1.X99] /// </summary> public StringEnumValue<MonthOrYear> InterestRateAdjTermLabel { get => _interestRateAdjTermLabel; set => SetField(ref _interestRateAdjTermLabel, value); } /// <summary> /// Loan Estimate - Interest Rate will Adjusts Every [LE1.X13] /// </summary> public string? InterestRateAdjustsEveryYears { get => _interestRateAdjustsEveryYears; set => SetField(ref _interestRateAdjustsEveryYears, value); } /// <summary> /// Loan Estimate - Interest Rate Will be Adjusted in Year/Month [LE1.X18] /// </summary> public int? InterestRateAdjustsInYear { get => _interestRateAdjustsInYear; set => SetField(ref _interestRateAdjustsInYear, value); } /// <summary> /// Loan Estimate - Interest Rate - Adjusts Starting in [LE1.X15] /// </summary> public StringEnumValue<MonthOrYear> InterestRateAdjustsStartingInType { get => _interestRateAdjustsStartingInType; set => SetField(ref _interestRateAdjustsStartingInType, value); } /// <summary> /// Loan Estimate - Interest Rate After Adjustment [LE1.X16] /// </summary> public int? InterestRateAfterAdjustment { get => _interestRateAfterAdjustment; set => SetField(ref _interestRateAfterAdjustment, value); } /// <summary> /// Loan Estimate - Interest Rate Can go or Goes [LE1.X17] /// </summary> public StringEnumValue<CanGoOrGoes> InterestRateCanGoGoes { get => _interestRateCanGoGoes; set => SetField(ref _interestRateCanGoGoes, value); } /// <summary> /// Loan Estimate - LE Date Issued [LE1.X1] /// </summary> public DateTime? LEDateIssued { get => _lEDateIssued; set => SetField(ref _lEDateIssued, value); } /// <summary> /// Loan Estimate - Loan Amount Can go or Goes [LE1.X10] /// </summary> public StringEnumValue<CanGoOrGoes> LoanAmountCanGoGoes { get => _loanAmountCanGoGoes; set => SetField(ref _loanAmountCanGoGoes, value); } /// <summary> /// Loan Estimate - Loan Amount Can increase or Increases [LE1.X11] /// </summary> public StringEnumValue<CanIncreaseOrIncreases> LoanAmountCanIncreaseOrIncreases { get => _loanAmountCanIncreaseOrIncreases; set => SetField(ref _loanAmountCanIncreaseOrIncreases, value); } /// <summary> /// Product Description [LE1.X5] /// </summary> public string? LoanProduct { get => _loanProduct; set => SetField(ref _loanProduct, value); } /// <summary> /// Loan Estimate - Loan Purpose [LE1.X4] /// </summary> public StringEnumValue<LoanEstimate1LoanPurpose> LoanPurpose { get => _loanPurpose; set => SetField(ref _loanPurpose, value); } /// <summary> /// Loan Estimate - Loan Term Months [LE1.X3] /// </summary> public int? LoanTermMonths { get => _loanTermMonths; set => SetField(ref _loanTermMonths, value); } /// <summary> /// Loan Estimate - Loan Term Years [LE1.X2] /// </summary> public int? LoanTermYears { get => _loanTermYears; set => SetField(ref _loanTermYears, value); } /// <summary> /// The calculated maximum monthly payment for a $10,000 loan [LE1.X93] /// </summary> public decimal? MaximumMonthlyPaymentFor10000Loan { get => _maximumMonthlyPaymentFor10000Loan; set => SetField(ref _maximumMonthlyPaymentFor10000Loan, value); } /// <summary> /// The calculated month in which the maximum monthly payment will go into effect [LE1.X94] /// </summary> public int? MaximumPaymentMonth { get => _maximumPaymentMonth; set => SetField(ref _maximumPaymentMonth, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - Will be Adjusted in Year/Month [LE1.X88] /// </summary> public StringEnumValue<MonthOrYear> MonthlyPIAdjustedInDateType { get => _monthlyPIAdjustedInDateType; set => SetField(ref _monthlyPIAdjustedInDateType, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest will Adjusts Every [LE1.X19] /// </summary> public string? MonthlyPIAdjustsEveryYears { get => _monthlyPIAdjustsEveryYears; set => SetField(ref _monthlyPIAdjustsEveryYears, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest Will be Adjusted in Year [LE1.X25] /// </summary> public int? MonthlyPIAdjustsInYear { get => _monthlyPIAdjustsInYear; set => SetField(ref _monthlyPIAdjustsInYear, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - Adjusts Starting in [LE1.X21] /// </summary> public StringEnumValue<MonthOrYear> MonthlyPIAdjustsStartingInType { get => _monthlyPIAdjustsStartingInType; set => SetField(ref _monthlyPIAdjustsStartingInType, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - Adjusts Every Months/Year/Years [LE1.X20] /// </summary> public StringEnumValue<TermType> MonthlyPIAdjustsTermType { get => _monthlyPIAdjustsTermType; set => SetField(ref _monthlyPIAdjustsTermType, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - After Adjustment [LE1.X22] /// </summary> public int? MonthlyPIAfterAdjustment { get => _monthlyPIAfterAdjustment; set => SetField(ref _monthlyPIAfterAdjustment, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest Can go or Goes [LE1.X23] /// </summary> public StringEnumValue<CanGoOrGoes> MonthlyPICanGoGoes { get => _monthlyPICanGoGoes; set => SetField(ref _monthlyPICanGoGoes, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - Interest Only in Year/Month [LE1.X89] /// </summary> public StringEnumValue<MonthOrYear> MonthlyPIInterestOnlyDateType { get => _monthlyPIInterestOnlyDateType; set => SetField(ref _monthlyPIInterestOnlyDateType, value); } /// <summary> /// Loan Estimate - Monthly Principal and Interest - Includes only interest and no principal until year [LE1.X26] /// </summary> public int? MonthlyPIInterestOnlyUntilYear { get => _monthlyPIInterestOnlyUntilYear; set => SetField(ref _monthlyPIInterestOnlyUntilYear, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Estimated Escrow Amount [LE1.X46] /// </summary> public int? PPC1EstimatedEscrowAmount { get => _pPC1EstimatedEscrowAmount; set => SetField(ref _pPC1EstimatedEscrowAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Estimated Escrow Amount UI Value [LE1.XD46] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC1EstimatedEscrowAmountUI { get => _pPC1EstimatedEscrowAmountUI; set => SetField(ref _pPC1EstimatedEscrowAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Interest Only [LE1.X44] /// </summary> public bool? PPC1InterestOnly { get => _pPC1InterestOnly; set => SetField(ref _pPC1InterestOnly, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Maximum Monthly Payment [LE1.X48] /// </summary> public decimal? PPC1MaximumMonthlyPayment { get => _pPC1MaximumMonthlyPayment; set => SetField(ref _pPC1MaximumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Maximum Monthly Payment UI Value [LE1.XD48] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC1MaximumMonthlyPaymentUI { get => _pPC1MaximumMonthlyPaymentUI; set => SetField(ref _pPC1MaximumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Maximum Principal and Interest Payment [LE1.X43] /// </summary> public decimal? PPC1MaximumPIPayment { get => _pPC1MaximumPIPayment; set => SetField(ref _pPC1MaximumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Maximum Principal and Interest Payment UI Value [LE1.XD43] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC1MaximumPIPaymentUI { get => _pPC1MaximumPIPaymentUI; set => SetField(ref _pPC1MaximumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Mortgage Insurance Amount [LE1.X45] /// </summary> public int? PPC1MIAmount { get => _pPC1MIAmount; set => SetField(ref _pPC1MIAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Mortgage Insurance Amount UI Value [LE1.XD45] /// </summary> public string? PPC1MIAmountUI { get => _pPC1MIAmountUI; set => SetField(ref _pPC1MIAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Minimum Monthly Payment [LE1.X47] /// </summary> public int? PPC1MinimumMonthlyPayment { get => _pPC1MinimumMonthlyPayment; set => SetField(ref _pPC1MinimumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Minimum Monthly Payment UI Value [LE1.XD47] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC1MinimumMonthlyPaymentUI { get => _pPC1MinimumMonthlyPaymentUI; set => SetField(ref _pPC1MinimumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Minimum Principal and Interest Payment [LE1.X42] /// </summary> public decimal? PPC1MinimumPIPayment { get => _pPC1MinimumPIPayment; set => SetField(ref _pPC1MinimumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Minimum Principal and Interest Payment UI Value [LE1.XD42] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC1MinimumPIPaymentUI { get => _pPC1MinimumPIPaymentUI; set => SetField(ref _pPC1MinimumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Year [LE1.X41] /// </summary> public int? PPC1Year { get => _pPC1Year; set => SetField(ref _pPC1Year, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Estimated Escrow Amount [LE1.X55] /// </summary> public int? PPC2EstimatedEscrowAmount { get => _pPC2EstimatedEscrowAmount; set => SetField(ref _pPC2EstimatedEscrowAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Estimated Escrow Amount UI Value [LE1.XD55] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2EstimatedEscrowAmountUI { get => _pPC2EstimatedEscrowAmountUI; set => SetField(ref _pPC2EstimatedEscrowAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Interest Only [LE1.X53] /// </summary> public bool? PPC2InterestOnly { get => _pPC2InterestOnly; set => SetField(ref _pPC2InterestOnly, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Maximum Monthly Payment [LE1.X57] /// </summary> public decimal? PPC2MaximumMonthlyPayment { get => _pPC2MaximumMonthlyPayment; set => SetField(ref _pPC2MaximumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Maximum Monthly Payment UI Value [LE1.XD57] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2MaximumMonthlyPaymentUI { get => _pPC2MaximumMonthlyPaymentUI; set => SetField(ref _pPC2MaximumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Maximum Principal and Interest Payment [LE1.X52] /// </summary> public decimal? PPC2MaximumPIPayment { get => _pPC2MaximumPIPayment; set => SetField(ref _pPC2MaximumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Maximum Principal and Interest Payment UI Value [LE1.XD52] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2MaximumPIPaymentUI { get => _pPC2MaximumPIPaymentUI; set => SetField(ref _pPC2MaximumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Mortgage Insurance Amount [LE1.X54] /// </summary> public int? PPC2MIAmount { get => _pPC2MIAmount; set => SetField(ref _pPC2MIAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Mortgage Insurance Amount UI Value [LE1.XD54] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2MIAmountUI { get => _pPC2MIAmountUI; set => SetField(ref _pPC2MIAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Minimum Monthly Payment [LE1.X56] /// </summary> public int? PPC2MinimumMonthlyPayment { get => _pPC2MinimumMonthlyPayment; set => SetField(ref _pPC2MinimumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Minimum Monthly Payment UI Value [LE1.XD56] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2MinimumMonthlyPaymentUI { get => _pPC2MinimumMonthlyPaymentUI; set => SetField(ref _pPC2MinimumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Minimum Principal and Interest Payment [LE1.X51] /// </summary> public decimal? PPC2MinimumPIPayment { get => _pPC2MinimumPIPayment; set => SetField(ref _pPC2MinimumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Minimum Principal and Interest Payment UI Value [LE1.XD51] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC2MinimumPIPaymentUI { get => _pPC2MinimumPIPaymentUI; set => SetField(ref _pPC2MinimumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Year From [LE1.X49] /// </summary> public int? PPC2YearFrom { get => _pPC2YearFrom; set => SetField(ref _pPC2YearFrom, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Year To [LE1.X50] /// </summary> public int? PPC2YearTo { get => _pPC2YearTo; set => SetField(ref _pPC2YearTo, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Estimated Escrow Amount [LE1.X64] /// </summary> public int? PPC3EstimatedEscrowAmount { get => _pPC3EstimatedEscrowAmount; set => SetField(ref _pPC3EstimatedEscrowAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Estimated Escrow Amount UI Value [LE1.XD64] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3EstimatedEscrowAmountUI { get => _pPC3EstimatedEscrowAmountUI; set => SetField(ref _pPC3EstimatedEscrowAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Interest Only [LE1.X62] /// </summary> public bool? PPC3InterestOnly { get => _pPC3InterestOnly; set => SetField(ref _pPC3InterestOnly, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Maximum Monthly Payment [LE1.X66] /// </summary> public decimal? PPC3MaximumMonthlyPayment { get => _pPC3MaximumMonthlyPayment; set => SetField(ref _pPC3MaximumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Maximum Monthly Payment UI Value [LE1.XD66] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3MaximumMonthlyPaymentUI { get => _pPC3MaximumMonthlyPaymentUI; set => SetField(ref _pPC3MaximumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Maximum Principal and Interest Payment [LE1.X61] /// </summary> public decimal? PPC3MaximumPIPayment { get => _pPC3MaximumPIPayment; set => SetField(ref _pPC3MaximumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Maximum Principal and Interest Payment UI Value [LE1.XD61] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3MaximumPIPaymentUI { get => _pPC3MaximumPIPaymentUI; set => SetField(ref _pPC3MaximumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Mortgage Insurance Amount [LE1.X63] /// </summary> public int? PPC3MIAmount { get => _pPC3MIAmount; set => SetField(ref _pPC3MIAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Mortgage Insurance Amount UI Value [LE1.XD63] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3MIAmountUI { get => _pPC3MIAmountUI; set => SetField(ref _pPC3MIAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Minimum Monthly Payment [LE1.X65] /// </summary> public int? PPC3MinimumMonthlyPayment { get => _pPC3MinimumMonthlyPayment; set => SetField(ref _pPC3MinimumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Minimum Monthly Payment UI Value [LE1.XD65] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3MinimumMonthlyPaymentUI { get => _pPC3MinimumMonthlyPaymentUI; set => SetField(ref _pPC3MinimumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Minimum Principal and Interest Payment [LE1.X60] /// </summary> public decimal? PPC3MinimumPIPayment { get => _pPC3MinimumPIPayment; set => SetField(ref _pPC3MinimumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Minimum Principal and Interest Payment UI Value [LE1.XD60] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC3MinimumPIPaymentUI { get => _pPC3MinimumPIPaymentUI; set => SetField(ref _pPC3MinimumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Year From [LE1.X58] /// </summary> public int? PPC3YearFrom { get => _pPC3YearFrom; set => SetField(ref _pPC3YearFrom, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Year To [LE1.X59] /// </summary> public int? PPC3YearTo { get => _pPC3YearTo; set => SetField(ref _pPC3YearTo, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Estimated Escrow Amount [LE1.X73] /// </summary> public int? PPC4EstimatedEscrowAmount { get => _pPC4EstimatedEscrowAmount; set => SetField(ref _pPC4EstimatedEscrowAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Estimated Escrow Amount UI Value [LE1.XD73] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4EstimatedEscrowAmountUI { get => _pPC4EstimatedEscrowAmountUI; set => SetField(ref _pPC4EstimatedEscrowAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Interest Only [LE1.X71] /// </summary> public bool? PPC4InterestOnly { get => _pPC4InterestOnly; set => SetField(ref _pPC4InterestOnly, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Maximum Monthly Payment [LE1.X75] /// </summary> public decimal? PPC4MaximumMonthlyPayment { get => _pPC4MaximumMonthlyPayment; set => SetField(ref _pPC4MaximumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Maximum Monthly Payment UI Value [LE1.XD75] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4MaximumMonthlyPaymentUI { get => _pPC4MaximumMonthlyPaymentUI; set => SetField(ref _pPC4MaximumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Maximum Principal and Interest Payment [LE1.X70] /// </summary> public decimal? PPC4MaximumPIPayment { get => _pPC4MaximumPIPayment; set => SetField(ref _pPC4MaximumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Maximum Principal and Interest Payment UI Value [LE1.XD70] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4MaximumPIPaymentUI { get => _pPC4MaximumPIPaymentUI; set => SetField(ref _pPC4MaximumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Mortgage Insurance Amount [LE1.X72] /// </summary> public int? PPC4MIAmount { get => _pPC4MIAmount; set => SetField(ref _pPC4MIAmount, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Mortgage Insurance Amount UI Value [LE1.XD72] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4MIAmountUI { get => _pPC4MIAmountUI; set => SetField(ref _pPC4MIAmountUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Minimum Monthly Payment [LE1.X74] /// </summary> public int? PPC4MinimumMonthlyPayment { get => _pPC4MinimumMonthlyPayment; set => SetField(ref _pPC4MinimumMonthlyPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Minimum Monthly Payment UI Value [LE1.XD74] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4MinimumMonthlyPaymentUI { get => _pPC4MinimumMonthlyPaymentUI; set => SetField(ref _pPC4MinimumMonthlyPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Minimum Principal and Interest Payment [LE1.X69] /// </summary> public decimal? PPC4MinimumPIPayment { get => _pPC4MinimumPIPayment; set => SetField(ref _pPC4MinimumPIPayment, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Minimum Principal and Interest Payment UI Value [LE1.XD69] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? PPC4MinimumPIPaymentUI { get => _pPC4MinimumPIPaymentUI; set => SetField(ref _pPC4MinimumPIPaymentUI, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Year From [LE1.X67] /// </summary> public int? PPC4YearFrom { get => _pPC4YearFrom; set => SetField(ref _pPC4YearFrom, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Year To [LE1.X68] /// </summary> public int? PPC4YearTo { get => _pPC4YearTo; set => SetField(ref _pPC4YearTo, value); } /// <summary> /// Loan Estimate - Projected Calculation - Estimated Escrow Indicator [LE1.X77] /// </summary> public bool? PPEstimatedEscrowIndicator { get => _pPEstimatedEscrowIndicator; set => SetField(ref _pPEstimatedEscrowIndicator, value); } /// <summary> /// Loan Estimate - Prepayment Penalty - If you pay off the loan during the first [LE1.X27] /// </summary> public int? PrepaymentPenaltyPayOffDuringYear { get => _prepaymentPenaltyPayOffDuringYear; set => SetField(ref _prepaymentPenaltyPayOffDuringYear, value); } /// <summary> /// Loan Estimate - Prepayment Penalty - In Year/Month [LE1.X91] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Month\"]")] public StringEnumValue<TermType> PrepaymentPenaltyPayOffInDateType { get => _prepaymentPenaltyPayOffInDateType; set => SetField(ref _prepaymentPenaltyPayOffInDateType, value); } /// <summary> /// Loan Estimate - Prepayment Penalty - In First Year [LE1.XD27] /// </summary> public string? PrepaymentPenaltyPayOffInFirstYear { get => _prepaymentPenaltyPayOffInFirstYear; set => SetField(ref _prepaymentPenaltyPayOffInFirstYear, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 1 - Range Payment Indicator [LE1.XD1] /// </summary> [LoanFieldProperty(ReadOnly = true)] public bool? RangePaymentIndicatorC1 { get => _rangePaymentIndicatorC1; set => SetField(ref _rangePaymentIndicatorC1, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 2 - Range Payment Indicator [LE1.XD2] /// </summary> [LoanFieldProperty(ReadOnly = true)] public bool? RangePaymentIndicatorC2 { get => _rangePaymentIndicatorC2; set => SetField(ref _rangePaymentIndicatorC2, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 3 - Range Payment Indicator [LE1.XD3] /// </summary> [LoanFieldProperty(ReadOnly = true)] public bool? RangePaymentIndicatorC3 { get => _rangePaymentIndicatorC3; set => SetField(ref _rangePaymentIndicatorC3, value); } /// <summary> /// Loan Estimate - Projected Calculation - Column 4 - Range Payment Indicator [LE1.XD4] /// </summary> [LoanFieldProperty(ReadOnly = true)] public bool? RangePaymentIndicatorC4 { get => _rangePaymentIndicatorC4; set => SetField(ref _rangePaymentIndicatorC4, value); } /// <summary> /// Loan Estimate - Rate Lock Expiration Time [LE1.X6] /// </summary> public string? RateLockExpirationTime { get => _rateLockExpirationTime; set => SetField(ref _rateLockExpirationTime, value); } /// <summary> /// Loan Estimate - Rate Lock Expiration Time Zone [LE1.X7] /// </summary> public string? RateLockExpirationTimeZone { get => _rateLockExpirationTimeZone; set => SetField(ref _rateLockExpirationTimeZone, value); } /// <summary> /// Loan Estimate - Reason Changed Circumstance Flags [LE1.X90] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? ReasonChangedCircumstanceFlags { get => _reasonChangedCircumstanceFlags; set => SetField(ref _reasonChangedCircumstanceFlags, value); } /// <summary> /// Delayed Settlement on Construction Loans [LE1.X83] /// </summary> public bool? ReasonDelayedSettlement { get => _reasonDelayedSettlement; set => SetField(ref _reasonDelayedSettlement, value); } /// <summary> /// Changed Circumstance - Eligibility [LE1.X79] /// </summary> public bool? ReasonEligibility { get => _reasonEligibility; set => SetField(ref _reasonEligibility, value); } /// <summary> /// Expiration (Intent to Proceed received after 10 business days) [LE1.X82] /// </summary> public bool? ReasonExpiration { get => _reasonExpiration; set => SetField(ref _reasonExpiration, value); } /// <summary> /// Interest Rate dependent charges (Rate Lock) [LE1.X81] /// </summary> public bool? ReasonInterestRate { get => _reasonInterestRate; set => SetField(ref _reasonInterestRate, value); } /// <summary> /// Other [LE1.X84] /// </summary> public bool? ReasonOther { get => _reasonOther; set => SetField(ref _reasonOther, value); } /// <summary> /// Other Description [LE1.X85] /// </summary> public string? ReasonOtherDescription { get => _reasonOtherDescription; set => SetField(ref _reasonOtherDescription, value); } /// <summary> /// Revisions requested by the consumer [LE1.X80] /// </summary> public bool? ReasonRevisions { get => _reasonRevisions; set => SetField(ref _reasonRevisions, value); } /// <summary> /// Changed Circumstance - Settlement Charges [LE1.X78] /// </summary> public bool? ReasonSettlementCharges { get => _reasonSettlementCharges; set => SetField(ref _reasonSettlementCharges, value); } /// <summary> /// Total Estimated Cash to Close [LE1.X87] /// </summary> public decimal? TotalEstimatedCashClose { get => _totalEstimatedCashClose; set => SetField(ref _totalEstimatedCashClose, value); } /// <summary> /// Loan Estimate - Year Until [LE1.X12] /// </summary> public int? YearsToRecast { get => _yearsToRecast; set => SetField(ref _yearsToRecast, value); } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.IO; using SharpDX.Direct3D11; using SharpDX.IO; namespace SharpDX.Toolkit.Graphics { /// <summary> /// A Texture 3D front end to <see cref="SharpDX.Direct3D11.Texture3D"/>. /// </summary> public class Texture3D : Texture3DBase { internal Texture3D(Device device, Texture3DDescription description3D, params DataBox[] dataBox) : base(device, description3D, dataBox) { } internal Texture3D(Device device, Direct3D11.Texture3D texture) : base(device, texture) { } internal override TextureView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipMapSlice) { throw new System.NotSupportedException(); } /// <summary> /// Makes a copy of this texture. /// </summary> /// <remarks> /// This method doesn't copy the content of the texture. /// </remarks> /// <returns> /// A copy of this texture. /// </returns> public override Texture Clone() { return new Texture3D(GraphicsDevice, this.Description); } /// <summary> /// Creates a new texture from a <see cref="Texture3DDescription"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="description">The description.</param> /// <returns> /// A new instance of <see cref="Texture3D"/> class. /// </returns> /// <msdn-id>ff476522</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short> public static Texture3D New(Device device, Texture3DDescription description) { return new Texture3D(device, description); } /// <summary> /// Creates a new texture from a <see cref="Direct3D11.Texture3D"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="texture">The native texture <see cref="Direct3D11.Texture3D"/>.</param> /// <returns> /// A new instance of <see cref="Texture3D"/> class. /// </returns> /// <msdn-id>ff476522</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short> public static Texture3D New(Device device, Direct3D11.Texture3D texture) { return new Texture3D(device, texture); } /// <summary> /// Creates a new <see cref="Texture3D"/> with a single mipmap. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <returns> /// A new instance of <see cref="Texture3D"/> class. /// </returns> /// <msdn-id>ff476522</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short> public static Texture3D New(Device device, int width, int height, int depth, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Default) { return New(device, width, height, depth, false, format, flags, usage); } /// <summary> /// Creates a new <see cref="Texture3D"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <returns> /// A new instance of <see cref="Texture3D"/> class. /// </returns> /// <msdn-id>ff476522</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short> public static Texture3D New(Device device, int width, int height, int depth, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Default) { return new Texture3D(device, NewDescription(width, height, depth, format, flags, mipCount, usage)); } /// <summary> /// Creates a new <see cref="Texture3D" /> with texture data for the firs map. /// </summary> /// <typeparam name="T">Type of the data to upload to the texture</typeparam> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="textureData">The texture data, width * height * depth data </param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <returns>A new instance of <see cref="Texture3D" /> class.</returns> /// <remarks> /// The first dimension of mipMapTextures describes the number of is an array ot Texture3D Array /// </remarks> /// <msdn-id>ff476522</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short> public unsafe static Texture3D New<T>(Device device, int width, int height, int depth, PixelFormat format, T[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) where T : struct { Texture3D texture = null; Utilities.Pin(textureData, ptr => { texture = New(device, width, height, depth, 1, format, new[] { GetDataBox(format, width, height, depth, textureData, ptr) }, flags, usage); }); return texture; } /// <summary> /// Creates a new <see cref="Texture3D"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="textureData">DataBox used to fill texture data.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <returns> /// A new instance of <see cref="Texture3D"/> class. /// </returns> /// <msdn-id>ff476522</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short> public static Texture3D New(Device device, int width, int height, int depth, MipMapCount mipCount, PixelFormat format, DataBox[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Default) { // TODO Add check for number of texture data according to width/height/depth/mipCount. return new Texture3D(device, NewDescription(width, height, depth, format, flags, mipCount, usage), textureData); } /// <summary> /// Creates a new <see cref="Texture3D" /> directly from an <see cref="Image"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="image">An image in CPU memory.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">The usage.</param> /// <returns>A new instance of <see cref="Texture3D" /> class.</returns> /// <msdn-id>ff476522</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short> public static Texture3D New(Device device, Image image, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { if (image == null) throw new ArgumentNullException("image"); if (image.Description.Dimension != TextureDimension.Texture3D) throw new ArgumentException("Invalid image. Must be 3D", "image"); return new Texture3D(device, CreateTextureDescriptionFromImage(image, flags, usage), image.ToDataBox()); } /// <summary> /// Loads a 3D texture from a stream. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="stream">The stream to load the texture from.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param> /// <exception cref="ArgumentException">If the texture is not of type 3D</exception> /// <returns>A texture</returns> public static new Texture3D Load(Device device, Stream stream, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { var texture = Texture.Load(device, stream, flags, usage); if (!(texture is Texture3D)) throw new ArgumentException(string.Format("Texture is not type of [Texture3D] but [{0}]", texture.GetType().Name)); return (Texture3D)texture; } /// <summary> /// Loads a 3D texture from a stream. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="filePath">The file to load the texture from.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param> /// <exception cref="ArgumentException">If the texture is not of type 3D</exception> /// <returns>A texture</returns> public static new Texture3D Load(Device device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read)) return Load(device, stream, flags, usage); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.ServiceModel.Channels.MessageHeaders.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel.Channels { sealed public partial class MessageHeaders : IEnumerable<MessageHeaderInfo>, System.Collections.IEnumerable { #region Methods and constructors public void Add(MessageHeader header) { } public void Clear() { } public void CopyHeaderFrom(Message message, int headerIndex) { Contract.Requires(message != null); Contract.Requires(0 <= headerIndex); Contract.Requires(headerIndex < message.Headers.Count); Contract.Requires(message.Headers.MessageVersion == this.MessageVersion); } public void CopyHeaderFrom(System.ServiceModel.Channels.MessageHeaders collection, int headerIndex) { Contract.Requires(collection != null); Contract.Requires(0 <= headerIndex); Contract.Requires(headerIndex < collection.Count); Contract.Requires(collection.MessageVersion == this.MessageVersion); } public void CopyHeadersFrom(Message message) { Contract.Requires(message != null); Contract.Requires(message.Headers != null); Contract.Requires(message.Headers.MessageVersion == this.MessageVersion); } public void CopyHeadersFrom(System.ServiceModel.Channels.MessageHeaders collection) { Contract.Requires(collection != null); Contract.Requires(collection.MessageVersion == this.MessageVersion); } public void CopyTo(MessageHeaderInfo[] array, int index) { Contract.Requires(array != null); Contract.Requires(0 <= index); Contract.Requires(index + this.Count <= array.Length); } public int FindHeader(string name, string ns) { Contract.Requires(name != null); Contract.Requires(ns != null); Contract.Ensures(-1 <= Contract.Result<int>()); return default(int); } public int FindHeader(string name, string ns, string[] actors) { Contract.Requires(name != null); Contract.Requires(ns != null); Contract.Requires(actors != null); Contract.Ensures(-1 <= Contract.Result<int>()); return default(int); } public IEnumerator<MessageHeaderInfo> GetEnumerator() { return default(IEnumerator<MessageHeaderInfo>); } public T GetHeader<T>(int index) { Contract.Ensures(Contract.Result<T>() != null); return default(T); } public T GetHeader<T>(int index, System.Runtime.Serialization.XmlObjectSerializer serializer) { Contract.Ensures(Contract.Result<T>() != null); return default(T); } public T GetHeader<T>(string name, string ns, System.Runtime.Serialization.XmlObjectSerializer serializer) { Contract.Ensures(Contract.Result<T>() != null); return default(T); } public T GetHeader<T>(string name, string ns) { Contract.Ensures(Contract.Result<T>() != null); return default(T); } public T GetHeader<T>(string name, string ns, string[] actors) { Contract.Ensures(Contract.Result<T>() != null); return default(T); } public System.Xml.XmlDictionaryReader GetReaderAtHeader(int headerIndex) { Contract.Requires(0 <= headerIndex); Contract.Requires(headerIndex < this.Count); return default(System.Xml.XmlDictionaryReader); } public bool HaveMandatoryHeadersBeenUnderstood() { return default(bool); } public bool HaveMandatoryHeadersBeenUnderstood(string[] actors) { Contract.Requires(actors != null); return default(bool); } public void Insert(int headerIndex, MessageHeader header) { Contract.Requires(header != null); Contract.Requires(header.IsMessageVersionSupported(this.MessageVersion)); Contract.Requires(0 <= headerIndex); Contract.Requires(headerIndex < this.Count); } public MessageHeaders(MessageVersion version, int initialSize) { Contract.Requires(version != null); Contract.Requires(0 <= initialSize); } public MessageHeaders(System.ServiceModel.Channels.MessageHeaders collection) { Contract.Requires(collection != null); } public MessageHeaders(MessageVersion version) { Contract.Requires(version != null); } public void RemoveAll(string name, string ns) { Contract.Requires(name != null); Contract.Requires(ns != null); } public void RemoveAt(int headerIndex) { Contract.Requires(0 <= headerIndex); Contract.Requires(headerIndex < this.Count); } public void SetAction(System.Xml.XmlDictionaryString action) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public void WriteHeader(int headerIndex, System.Xml.XmlDictionaryWriter writer) { Contract.Requires(0 <= headerIndex); Contract.Requires(headerIndex < this.Count); Contract.Requires(writer != null); } public void WriteHeader(int headerIndex, System.Xml.XmlWriter writer) { Contract.Requires(0 <= headerIndex); Contract.Requires(headerIndex < this.Count); Contract.Requires(writer != null); } public void WriteHeaderContents(int headerIndex, System.Xml.XmlDictionaryWriter writer) { Contract.Requires(0 <= headerIndex); Contract.Requires(headerIndex < this.Count); Contract.Requires(writer != null); } public void WriteHeaderContents(int headerIndex, System.Xml.XmlWriter writer) { Contract.Requires(0 <= headerIndex); Contract.Requires(headerIndex < this.Count); Contract.Requires(writer != null); } public void WriteStartHeader(int headerIndex, System.Xml.XmlDictionaryWriter writer) { Contract.Requires(0 <= headerIndex); Contract.Requires(headerIndex < this.Count); Contract.Requires(writer != null); } public void WriteStartHeader(int headerIndex, System.Xml.XmlWriter writer) { Contract.Requires(0 <= headerIndex); Contract.Requires(headerIndex < this.Count); Contract.Requires(writer != null); } #endregion #region Properties and indexers public string Action { get { return default(string); } set { } } public int Count { get { return default(int); } } public System.ServiceModel.EndpointAddress FaultTo { get { return default(System.ServiceModel.EndpointAddress); } set { } } public System.ServiceModel.EndpointAddress From { get { return default(System.ServiceModel.EndpointAddress); } set { } } public MessageHeaderInfo this [int index] { get { return default(MessageHeaderInfo); } } public System.Xml.UniqueId MessageId { get { return default(System.Xml.UniqueId); } set { } } public MessageVersion MessageVersion { get { Contract.Ensures(Contract.Result<MessageVersion>() != null); return default(MessageVersion); } } public System.Xml.UniqueId RelatesTo { get { return default(System.Xml.UniqueId); } set { Contract.Requires(value != null); } } public System.ServiceModel.EndpointAddress ReplyTo { get { return default(System.ServiceModel.EndpointAddress); } set { } } public Uri To { get { return default(Uri); } set { } } public UnderstoodHeaders UnderstoodHeaders { get { Contract.Ensures(Contract.Result<System.ServiceModel.Channels.UnderstoodHeaders>() != null); return default(UnderstoodHeaders); } } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Authorization; using Microsoft.Azure.Management.Authorization.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Authorization { /// <summary> /// Get resource or resource group permissions (see http://TBD for more /// information) /// </summary> internal partial class PermissionOperations : IServiceOperations<AuthorizationManagementClient>, IPermissionOperations { /// <summary> /// Initializes a new instance of the PermissionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PermissionOperations(AuthorizationManagementClient client) { this._client = client; } private AuthorizationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Authorization.AuthorizationManagementClient. /// </summary> public AuthorizationManagementClient Client { get { return this._client; } } /// <summary> /// Gets a resource permissions. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Permissions information. /// </returns> public async Task<PermissionGetResult> ListForResourceAsync(string resourceGroupName, ResourceIdentity identity, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (identity == null) { throw new ArgumentNullException("identity"); } if (identity.ResourceName == null) { throw new ArgumentNullException("identity."); } if (identity.ResourceProviderNamespace == null) { throw new ArgumentNullException("identity."); } if (identity.ResourceType == null) { throw new ArgumentNullException("identity."); } // 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("identity", identity); TracingAdapter.Enter(invocationId, this, "ListForResourceAsync", 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 + Uri.EscapeDataString(identity.ResourceProviderNamespace); url = url + "/"; if (identity.ParentResourcePath != null) { url = url + identity.ParentResourcePath; } url = url + "/"; url = url + identity.ResourceType; url = url + "/"; url = url + Uri.EscapeDataString(identity.ResourceName); url = url + "/providers/Microsoft.Authorization/permissions"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-07-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // 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 PermissionGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PermissionGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Permission permissionInstance = new Permission(); result.Permissions.Add(permissionInstance); JToken actionsArray = valueValue["actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { permissionInstance.Actions.Add(((string)actionsValue)); } } JToken notActionsArray = valueValue["notActions"]; if (notActionsArray != null && notActionsArray.Type != JTokenType.Null) { foreach (JToken notActionsValue in ((JArray)notActionsArray)) { permissionInstance.NotActions.Add(((string)notActionsValue)); } } } } } } 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 a resource group permissions. /// </summary> /// <param name='resourceGroupName'> /// Required. Name of the resource group to get the permissions for.The /// name is case insensitive. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Permissions information. /// </returns> public async Task<PermissionGetResult> ListForResourceGroupAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } // 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); TracingAdapter.Enter(invocationId, this, "ListForResourceGroupAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.Authorization/permissions"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-07-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // 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 PermissionGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PermissionGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Permission permissionInstance = new Permission(); result.Permissions.Add(permissionInstance); JToken actionsArray = valueValue["actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { permissionInstance.Actions.Add(((string)actionsValue)); } } JToken notActionsArray = valueValue["notActions"]; if (notActionsArray != null && notActionsArray.Type != JTokenType.Null) { foreach (JToken notActionsValue in ((JArray)notActionsArray)) { permissionInstance.NotActions.Add(((string)notActionsValue)); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// // Copyright (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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Management.Network.Models; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Network Management API includes operations for managing the /// gateways for your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for /// more information) /// </summary> public partial interface IGatewayOperations { /// <summary> /// To connect to, disconnect from, or test your connection to a local /// network site, access the connection resource representing the /// local network and specify Connect, Disconnect or Test to perform /// the desired operation. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154107.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='localNetworkSiteName'> /// The name of the site to connect to. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Connect Disconnect Or Testing /// Gateway operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginConnectDisconnectOrTestingAsync(string networkName, string localNetworkSiteName, GatewayConnectDisconnectOrTestParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Creating Virtual network Gateway operation creates a new /// network gateway for the specified virtual network in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Creating Virtual Network Gateway /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginCreatingAsync(string networkName, GatewayCreateParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Deleting Virtual Network Gateway operation deletes a /// network gateway for the specified virtual network in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154129.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginDeletingAsync(string networkName, CancellationToken cancellationToken); /// <summary> /// The Begin Failover Virtual Network Gateway operation causes a /// network gateway failover for the specified virtual network in /// Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154118.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network in Azure. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginFailoverAsync(string networkName, CancellationToken cancellationToken); /// <summary> /// The Generate VPN Client Package operation creates a VPN client /// package for the specified virtual network and gateway in Azure. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205126.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Generate VPN Client Package operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginGenerateVpnClientPackageAsync(string networkName, GatewayGenerateVpnClientPackageParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Remove Virtual Network Gateway Shared Key operation /// removes the default sites on the virtual network gateway for the /// specified virtual network. /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginRemoveDefaultSitesAsync(string networkName, CancellationToken cancellationToken); /// <summary> /// The Begin Reset Virtual Network Gateway Shared Key operation resets /// the shared key on the virtual network gateway for the specified /// virtual network connection to the specified local network in /// Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='localNetworkName'> /// The name of the local network. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Virtual Network Gateway Reset /// Shared Key request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginResetSharedKeyAsync(string networkName, string localNetworkName, GatewayResetSharedKeyParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Resize Virtual network Gateway operation resizes an /// existing gateway to a different GatewaySKU. /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Resize Virtual Network Gateway /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginResizeAsync(string networkName, ResizeGatewayParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Set Virtual Network Gateway Shared Key operation sets the /// default sites on the virtual network gateway for the specified /// virtual network. /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Virtual Network Gateway Set /// Default Sites request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginSetDefaultSitesAsync(string networkName, GatewaySetDefaultSiteListParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Set Virtual Network Gateway IPsec Parameters operation /// sets the IPsec parameters on the virtual network gateway for the /// specified connection to the specified local network in Azure. /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='localNetworkName'> /// The name of the local network. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Virtual Network Gateway Set IPsec /// Parameters request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginSetIPsecParametersAsync(string networkName, string localNetworkName, GatewaySetIPsecParametersParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Set Virtual Network Gateway Shared Key operation sets the /// shared key on the virtual network gateway for the specified /// virtual network connection to the specified local network in /// Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='localNetworkName'> /// The name of the local network. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Virtual Network Gateway Set Shared /// Key request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginSetSharedKeyAsync(string networkName, string localNetworkName, GatewaySetSharedKeyParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Start Diagnostics operation begins an asynchronous /// operation to starta diagnostics session for the specified virtual /// network gateway in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Start Diagnostics operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> BeginStartDiagnosticsAsync(string networkName, StartGatewayPublicDiagnosticsParameters parameters, CancellationToken cancellationToken); /// <summary> /// To connect to, disconnect from, or test your connection to a local /// network site, access the connection resource representing the /// local network and specify Connect, Disconnect or Test to perform /// the desired operation. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154107.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='localNetworkSiteName'> /// The name of the site to connect to. /// </param> /// <param name='parameters'> /// Parameters supplied to the Connect Disconnect Or Testing Gateway /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> ConnectDisconnectOrTestAsync(string networkName, string localNetworkSiteName, GatewayConnectDisconnectOrTestParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Create Virtual network Gateway operation creates a new network /// gateway for the specified virtual network in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Network Gateway operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> CreateAsync(string networkName, GatewayCreateParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Delete Virtual Network Gateway operation deletes a network /// gateway for the specified virtual network in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154129.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> DeleteAsync(string networkName, CancellationToken cancellationToken); /// <summary> /// The Failover Virtual Network Gateway operation causes a network /// gateway failover for the specified virtual network in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154118.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network in Azure. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> FailoverAsync(string networkName, CancellationToken cancellationToken); /// <summary> /// The Generate VPN Client Package operation creates a VPN client /// package for the specified virtual network and gateway in Azure. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Generate VPN Client Package operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> GenerateVpnClientPackageAsync(string networkName, GatewayGenerateVpnClientPackageParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Get Virtual Network Gateway operation gets information about /// the network gateway for the specified virtual network in Azure. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154109.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayGetResponse> GetAsync(string networkName, CancellationToken cancellationToken); /// <summary> /// The Get Device Configuration Script operation returns a script that /// you can use to configure local VPN devices to connect to the /// gateway. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154115.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// The parameters for the Get Device Configuration Script operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The configuration script returned from the get device configuration /// script operation. /// </returns> Task<GatewayGetDeviceConfigurationScriptResponse> GetDeviceConfigurationScriptAsync(string networkName, GatewayGetDeviceConfigurationScriptParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Get Diagnostics operation gets information about the current /// gateway diagnostics session for the specified virtual network in /// Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The status of a gateway diagnostics operation. /// </returns> Task<GatewayDiagnosticsStatus> GetDiagnosticsAsync(string networkName, CancellationToken cancellationToken); /// <summary> /// The Get IPsec Parameters operation gets the IPsec parameters that /// have been set for the connection between the provided virtual /// network gateway and the provided local network site. /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='localNetworkName'> /// The name of the local network. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response that will be returned from a GetIPsecParameters /// request. This contains the IPsec parameters for the specified /// connection. /// </returns> Task<GatewayGetIPsecParametersResponse> GetIPsecParametersAsync(string networkName, string localNetworkName, CancellationToken cancellationToken); /// <summary> /// The Get Virtual Network Gateway Operation Status gets information /// on the status of network gateway operations in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx /// for more information) /// </summary> /// <param name='operationId'> /// The ID of the network operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> GetOperationStatusAsync(string operationId, CancellationToken cancellationToken); /// <summary> /// The Get Virtual Network Gateway Shared Key operation gets the /// shared key on the virtual network gateway for the specified /// virtual network connection to the specified local network in /// Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154122.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='localNetworkName'> /// The name of the local network. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response to the get shared key request. /// </returns> Task<GatewayGetSharedKeyResponse> GetSharedKeyAsync(string networkName, string localNetworkName, CancellationToken cancellationToken); /// <summary> /// The List Connections operation returns a list of the local network /// connections that can be accessed through the gateway. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154120.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response to a ListConnections request to a Virtual Network /// Gateway. /// </returns> Task<GatewayListConnectionsResponse> ListConnectionsAsync(string networkName, CancellationToken cancellationToken); /// <summary> /// The List Virtual Network Gateway Supported Devices operation lists /// the supported, on-premise network devices that can connect to the /// gateway. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154102.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response to the list supported devices request. /// </returns> Task<GatewayListSupportedDevicesResponse> ListSupportedDevicesAsync(CancellationToken cancellationToken); /// <summary> /// The Remove Virtual Network Gateway Shared Key operation sets the /// default sites on the virtual network gateway for the specified /// virtual network. /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> RemoveDefaultSitesAsync(string networkName, CancellationToken cancellationToken); /// <summary> /// The Reset Virtual Network Gateway Shared Key operation resets the /// shared key on the virtual network gateway for the specified /// virtual network connection to the specified local network in /// Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='localNetworkName'> /// The name of the local network. /// </param> /// <param name='parameters'> /// The parameters to the Virtual Network Gateway Reset Shared Key /// request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> ResetSharedKeyAsync(string networkName, string localNetworkName, GatewayResetSharedKeyParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Resize Virtual network Gateway operation resizes an /// existing gateway to a different GatewaySKU. /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Resize Virtual Network Gateway operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> ResizeAsync(string networkName, ResizeGatewayParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Set Virtual Network Gateway Shared Key operation sets the /// default sites on the virtual network gateway for the specified /// virtual network. /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Virtual Network Gateway Set /// Default Sites request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> SetDefaultSitesAsync(string networkName, GatewaySetDefaultSiteListParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Set Virtual Network Gateway IPsec Parameters operation /// sets the IPsec parameters on the virtual network gateway for the /// specified connection to the specified local network in Azure. /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='localNetworkName'> /// The name of the local network. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Virtual Network Gateway Set IPsec /// Parameters request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> SetIPsecParametersAsync(string networkName, string localNetworkName, GatewaySetIPsecParametersParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Set Virtual Network Gateway Shared Key operation sets the /// shared key on the virtual network gateway for the specified /// virtual network connection to the specified local network in /// Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='localNetworkName'> /// The name of the local network. /// </param> /// <param name='parameters'> /// The parameters to the Virtual Network Gateway Set Shared Key /// request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> SetSharedKeyAsync(string networkName, string localNetworkName, GatewaySetSharedKeyParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Start Diagnostics operation starts a diagnostics session for /// the specified virtual network gateway in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Start Diagnostics operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is in progress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<GatewayGetOperationStatusResponse> StartDiagnosticsAsync(string networkName, StartGatewayPublicDiagnosticsParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Stop Diagnostics operation begins an asynchronous operation to /// stopa diagnostics session for the specified virtual network /// gateway in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx /// for more information) /// </summary> /// <param name='networkName'> /// The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to Stop Diagnostics operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GatewayOperationResponse> StopDiagnosticsAsync(string networkName, StopGatewayPublicDiagnosticsParameters parameters, CancellationToken cancellationToken); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ValveResourceFormat.Serialization.NTRO { public class NTROStruct : IDictionary, IKeyValueCollection { private readonly Dictionary<string, NTROValue> Contents; public string Name { get; private set; } public NTROStruct(string name) { Name = name; Contents = new Dictionary<string, NTROValue>(); } public NTROStruct(params NTROValue[] values) { Contents = new Dictionary<string, NTROValue>(); for (var i = 0; i < values.Length; i++) { Contents.Add(i.ToString(), values[i]); } } public void WriteText(IndentedTextWriter writer) { writer.WriteLine(Name); writer.WriteLine("{"); writer.Indent++; foreach (var entry in Contents) { var array = entry.Value as NTROArray; var byteArray = (entry.Value as NTROValue<byte[]>)?.Value; if (entry.Value.Pointer) { writer.Write("{0} {1}* = (ptr) ->", ValveDataType(entry.Value.Type), entry.Key); entry.Value.WriteText(writer); } else if (array != null) { writer.WriteLine("{0} {1}[{2}] =", ValveDataType(array.Type), entry.Key, array.Count); writer.WriteLine("["); writer.Indent++; foreach (var innerEntry in array) { innerEntry.WriteText(writer); } writer.Indent--; writer.WriteLine("]"); } else if (byteArray != null) { writer.WriteLine("{0}[{2}] {1} =", ValveDataType(entry.Value.Type), entry.Key, byteArray.Length); writer.WriteLine("["); writer.Indent++; foreach (var val in byteArray) { writer.WriteLine("{0:X2}", val); } writer.Indent--; writer.WriteLine("]"); } else { // Can either be NTROArray or NTROValue so... writer.Write("{0} {1} = ", ValveDataType(entry.Value.Type), entry.Key); entry.Value.WriteText(writer); } } writer.Indent--; writer.WriteLine("}"); } public override string ToString() { using (var writer = new IndentedTextWriter()) { WriteText(writer); return writer.ToString(); } } private static string ValveDataType(DataType type) { switch (type) { case DataType.SByte: return "int8"; case DataType.Byte: return "uint8"; case DataType.Int16: return "int16"; case DataType.UInt16: return "uint16"; case DataType.Int32: return "int32"; case DataType.UInt32: return "uint32"; case DataType.Int64: return "int64"; case DataType.UInt64: return "uint64"; case DataType.Float: return "float32"; case DataType.String: return "CResourceString"; case DataType.Boolean: return "bool"; case DataType.Fltx4: return "fltx4"; case DataType.Matrix3x4a: return "matrix3x4a_t"; } return type.ToString(); } public NTROValue this[string key] { get => Contents[key]; set => Contents[key] = value; } public object this[object key] { get => ((IDictionary)Contents)[key]; set => ((IDictionary)Contents)[key] = value; } public int Count => Contents.Count; public bool IsFixedSize => ((IDictionary)Contents).IsFixedSize; public bool IsReadOnly => ((IDictionary)Contents).IsReadOnly; public bool IsSynchronized => ((IDictionary)Contents).IsSynchronized; public ICollection Keys => Contents.Keys; public object SyncRoot => ((IDictionary)Contents).SyncRoot; public ICollection Values => Contents.Values; public void Add(object key, object value) { ((IDictionary)Contents).Add(key, value); } public void Clear() { Contents.Clear(); } public bool Contains(object key) { return ((IDictionary)Contents).Contains(key); } public void CopyTo(Array array, int index) { ((IDictionary)Contents).CopyTo(array, index); } public IDictionaryEnumerator GetEnumerator() { return ((IDictionary)Contents).GetEnumerator(); } public void Remove(object key) { ((IDictionary)Contents).Remove(key); } IEnumerator IEnumerable.GetEnumerator() { return ((IDictionary)Contents).GetEnumerator(); } public bool ContainsKey(string name) => Contents.ContainsKey(name); public T[] GetArray<T>(string name) { if (Contents.TryGetValue(name, out var value)) { if (value.Type == DataType.Byte) { //special case for byte arrays for faster access if (typeof(T) == typeof(byte)) { return (T[])value.ValueObject; } else { //still have to do a slow conversion if the requested type is different return ((byte[])value.ValueObject).Select(v => (T)(object)v).ToArray(); } } else { return ((NTROArray)value).Select(v => (T)v.ValueObject).ToArray(); } } else { return default(T[]); } } public T GetProperty<T>(string name) { if (Contents.TryGetValue(name, out var value)) { return (T)value.ValueObject; } else { return default(T); } } IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() => Contents .Select(p => new KeyValuePair<string, object>(p.Key, p.Value.ValueObject)) .GetEnumerator(); } }
using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Util; using Lucene.Net.Util.Packed; using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Codecs.BlockTerms { /* * 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> /// Selects every Nth term as and index term, and hold term /// bytes (mostly) fully expanded in memory. This terms index /// supports seeking by ord. See /// <see cref="VariableGapTermsIndexWriter"/> for a more memory efficient /// terms index that does not support seeking by ord. /// <para/> /// @lucene.experimental /// </summary> public class FixedGapTermsIndexWriter : TermsIndexWriterBase { protected IndexOutput m_output; /// <summary>Extension of terms index file</summary> internal readonly static string TERMS_INDEX_EXTENSION = "tii"; internal readonly static string CODEC_NAME = "SIMPLE_STANDARD_TERMS_INDEX"; internal readonly static int VERSION_START = 0; internal readonly static int VERSION_APPEND_ONLY = 1; internal readonly static int VERSION_CHECKSUM = 1000; // 4.x "skipped" trunk's monotonic addressing: give any user a nice exception internal readonly static int VERSION_CURRENT = VERSION_CHECKSUM; private readonly int termIndexInterval; private readonly IList<SimpleFieldWriter> fields = new List<SimpleFieldWriter>(); //private readonly FieldInfos fieldInfos; // unread // LUCENENET: Not used public FixedGapTermsIndexWriter(SegmentWriteState state) { string indexFileName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, TERMS_INDEX_EXTENSION); termIndexInterval = state.TermIndexInterval; m_output = state.Directory.CreateOutput(indexFileName, state.Context); bool success = false; try { //fieldInfos = state.FieldInfos; // LUCENENET: Not used WriteHeader(m_output); m_output.WriteInt32(termIndexInterval); success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(m_output); } } } private void WriteHeader(IndexOutput output) { CodecUtil.WriteHeader(output, CODEC_NAME, VERSION_CURRENT); } public override FieldWriter AddField(FieldInfo field, long termsFilePointer) { //System.out.println("FGW: addFfield=" + field.name); SimpleFieldWriter writer = new SimpleFieldWriter(this, field, termsFilePointer); fields.Add(writer); return writer; } /// <summary> /// NOTE: if your codec does not sort in unicode code /// point order, you must override this method, to simply /// return <c>indexedTerm.Length</c>. /// </summary> protected virtual int IndexedTermPrefixLength(BytesRef priorTerm, BytesRef indexedTerm) { // As long as codec sorts terms in unicode codepoint // order, we can safely strip off the non-distinguishing // suffix to save RAM in the loaded terms index. int idxTermOffset = indexedTerm.Offset; int priorTermOffset = priorTerm.Offset; int limit = Math.Min(priorTerm.Length, indexedTerm.Length); for (int byteIdx = 0; byteIdx < limit; byteIdx++) { if (priorTerm.Bytes[priorTermOffset + byteIdx] != indexedTerm.Bytes[idxTermOffset + byteIdx]) { return byteIdx + 1; } } return Math.Min(1 + priorTerm.Length, indexedTerm.Length); } private class SimpleFieldWriter : FieldWriter { private readonly FixedGapTermsIndexWriter outerInstance; internal readonly FieldInfo fieldInfo; internal int numIndexTerms; internal readonly long indexStart; internal readonly long termsStart; internal long packedIndexStart; internal long packedOffsetsStart; private long numTerms; // TODO: we could conceivably make a PackedInts wrapper // that auto-grows... then we wouldn't force 6 bytes RAM // per index term: private short[] termLengths; private int[] termsPointerDeltas; private long lastTermsPointer; private long totTermLength; private readonly BytesRef lastTerm = new BytesRef(); internal SimpleFieldWriter(FixedGapTermsIndexWriter outerInstance, FieldInfo fieldInfo, long termsFilePointer) { this.outerInstance = outerInstance; this.fieldInfo = fieldInfo; indexStart = outerInstance.m_output.GetFilePointer(); termsStart = lastTermsPointer = termsFilePointer; termLengths = EMPTY_INT16S; termsPointerDeltas = EMPTY_INT32S; } public override bool CheckIndexTerm(BytesRef text, TermStats stats) { // First term is first indexed term: //System.output.println("FGW: checkIndexTerm text=" + text.utf8ToString()); if (0 == (numTerms++ % outerInstance.termIndexInterval)) { return true; } else { if (0 == numTerms % outerInstance.termIndexInterval) { // save last term just before next index term so we // can compute wasted suffix lastTerm.CopyBytes(text); } return false; } } public override void Add(BytesRef text, TermStats stats, long termsFilePointer) { int indexedTermLength = outerInstance.IndexedTermPrefixLength(lastTerm, text); //System.out.println("FGW: add text=" + text.utf8ToString() + " " + text + " fp=" + termsFilePointer); // write only the min prefix that shows the diff // against prior term outerInstance.m_output.WriteBytes(text.Bytes, text.Offset, indexedTermLength); if (termLengths.Length == numIndexTerms) { termLengths = ArrayUtil.Grow(termLengths); } if (termsPointerDeltas.Length == numIndexTerms) { termsPointerDeltas = ArrayUtil.Grow(termsPointerDeltas); } // save delta terms pointer termsPointerDeltas[numIndexTerms] = (int)(termsFilePointer - lastTermsPointer); lastTermsPointer = termsFilePointer; // save term length (in bytes) if (Debugging.AssertsEnabled) Debugging.Assert(indexedTermLength <= short.MaxValue); termLengths[numIndexTerms] = (short)indexedTermLength; totTermLength += indexedTermLength; lastTerm.CopyBytes(text); numIndexTerms++; } public override void Finish(long termsFilePointer) { // write primary terms dict offsets packedIndexStart = outerInstance.m_output.GetFilePointer(); PackedInt32s.Writer w = PackedInt32s.GetWriter(outerInstance.m_output, numIndexTerms, PackedInt32s.BitsRequired(termsFilePointer), PackedInt32s.DEFAULT); // relative to our indexStart long upto = 0; for (int i = 0; i < numIndexTerms; i++) { upto += termsPointerDeltas[i]; w.Add(upto); } w.Finish(); packedOffsetsStart = outerInstance.m_output.GetFilePointer(); // write offsets into the byte[] terms w = PackedInt32s.GetWriter(outerInstance.m_output, 1 + numIndexTerms, PackedInt32s.BitsRequired(totTermLength), PackedInt32s.DEFAULT); upto = 0; for (int i = 0; i < numIndexTerms; i++) { w.Add(upto); upto += termLengths[i]; } w.Add(upto); w.Finish(); // our referrer holds onto us, while other fields are // being written, so don't tie up this RAM: termLengths = null; termsPointerDeltas = null; } } protected override void Dispose(bool disposing) { if (disposing) { if (m_output != null) { bool success = false; try { long dirStart = m_output.GetFilePointer(); int fieldCount = fields.Count; int nonNullFieldCount = 0; for (int i = 0; i < fieldCount; i++) { SimpleFieldWriter field = fields[i]; if (field.numIndexTerms > 0) { nonNullFieldCount++; } } m_output.WriteVInt32(nonNullFieldCount); for (int i = 0; i < fieldCount; i++) { SimpleFieldWriter field = fields[i]; if (field.numIndexTerms > 0) { m_output.WriteVInt32(field.fieldInfo.Number); m_output.WriteVInt32(field.numIndexTerms); m_output.WriteVInt64(field.termsStart); m_output.WriteVInt64(field.indexStart); m_output.WriteVInt64(field.packedIndexStart); m_output.WriteVInt64(field.packedOffsetsStart); } } WriteTrailer(dirStart); CodecUtil.WriteFooter(m_output); success = true; } finally { if (success) { IOUtils.Dispose(m_output); } else { IOUtils.DisposeWhileHandlingException(m_output); } m_output = null; } } } } private void WriteTrailer(long dirStart) { m_output.WriteInt64(dirStart); } } }
using System; using System.Text; using TestLibrary; class EncodingGetBytes1 { static int Main() { EncodingGetBytes1 test = new EncodingGetBytes1(); TestFramework.BeginTestCase("Encoding.GetBytes"); if (test.RunTests()) { TestFramework.EndTestCase(); TestFramework.LogInformation("PASS"); return 100; } else { TestFramework.EndTestCase(); TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool ret = true; ret &= Test1(); ret &= Test2(); ret &= Test3(); ret &= Test4(); ret &= Test5(); ret &= Test6(); ret &= Test7(); ret &= Test8(); ret &= Test9(); ret &= Test10(); ret &= Test11(); ret &= Test12(); ret &= Test13(); ret &= Test40(); ret &= Test41(); ret &= Test42(); ret &= Test43(); ret &= Test44(); ret &= Test45(); ret &= Test46(); ret &= Test47(); ret &= Test48(); ret &= Test49(); ret &= Test50(); ret &= Test51(); ret &= Test52(); ret &= Test53(); ret &= Test54(); ret &= Test55(); ret &= Test56(); ret &= Test57(); ret &= Test58(); ret &= Test59(); ret &= Test60(); ret &= Test61(); ret &= Test62(); ret &= Test63(); ret &= Test64(); ret &= Test65(); ret &= Test66(); ret &= Test69(); ret &= Test70(); ret &= Test71(); ret &= Test74(); ret &= Test75(); ret &= Test76(); ret &= Test7(); ret &= Test79(); ret &= Test80(); ret &= Test81(); ret &= Test82(); ret &= Test83(); ret &= Test84(); ret &= Test85(); ret &= Test96(); ret &= Test97(); ret &= Test98(); ret &= Test99(); ret &= Test100(); ret &= Test101(); ret &= Test102(); ret &= Test103(); ret &= Test104(); ret &= Test105(); ret &= Test106(); ret &= Test107(); ret &= Test108(); ret &= Test109(); ret &= Test110(); ret &= Test111(); ret &= Test112(); ret &= Test113(); ret &= Test114(); ret &= Test133(); ret &= Test134(); ret &= Test135(); ret &= Test136(); ret &= Test137(); ret &= Test138(); ret &= Test139(); ret &= Test140(); ret &= Test141(); ret &= Test142(); ret &= Test143(); ret &= Test144(); ret &= Test145(); ret &= Test146(); ret &= Test147(); ret &= Test148(); ret &= Test149(); ret &= Test150(); ret &= Test151(); ret &= Test152(); ret &= Test153(); ret &= Test154(); ret &= Test155(); ret &= Test156(); ret &= Test157(); ret &= Test158(); ret &= Test159(); ret &= Test107(); ret &= Test179(); ret &= Test180(); ret &= Test181(); ret &= Test182(); ret &= Test183(); ret &= Test184(); ret &= Test185(); ret &= Test186(); ret &= Test187(); ret &= Test188(); ret &= Test189(); ret &= Test190(); ret &= Test191(); ret &= Test192(); ret &= Test193(); ret &= Test194(); ret &= Test195(); return ret; } // Positive Tests public bool Test1() { return PositiveTestString(Encoding.UTF8, "TestString", new byte[] { 84, 101, 115, 116, 83, 116, 114, 105, 110, 103 }, "00A"); } public bool Test2() { return PositiveTestString(Encoding.UTF8, "", new byte[] { }, "00B"); } public bool Test3() { return PositiveTestString(Encoding.UTF8, "FooBA\u0400R", new byte[] { 70, 111, 111, 66, 65, 208, 128, 82 }, "00C"); } public bool Test4() { return PositiveTestString(Encoding.UTF8, "\u00C0nima\u0300l", new byte[] { 195, 128, 110, 105, 109, 97, 204, 128, 108 }, "00D"); } public bool Test5() { return PositiveTestString(Encoding.UTF8, "Test\uD803\uDD75Test", new byte[] { 84, 101, 115, 116, 240, 144, 181, 181, 84, 101, 115, 116 }, "00E"); } public bool Test6() { return PositiveTestString(Encoding.UTF8, "Test\uD803Test", new byte[] { 84, 101, 115, 116, 239, 191, 189, 84, 101, 115, 116 }, "00F"); } public bool Test7() { return PositiveTestString(Encoding.UTF8, "Test\uDD75Test", new byte[] { 84, 101, 115, 116, 239, 191, 189, 84, 101, 115, 116 }, "00G"); } public bool Test8() { return PositiveTestString(Encoding.UTF8, "TestTest\uDD75", new byte[] { 84, 101, 115, 116, 84, 101, 115, 116, 239, 191, 189 }, "00H"); } public bool Test9() { return PositiveTestString(Encoding.UTF8, "TestTest\uD803", new byte[] { 84, 101, 115, 116, 84, 101, 115, 116, 239, 191, 189 }, "00I"); } public bool Test10() { return PositiveTestString(Encoding.UTF8, "\uDD75", new byte[] { 239, 191, 189 }, "00J"); } public bool Test11() { return PositiveTestString(Encoding.UTF8, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 181, 181 }, "00K"); } public bool Test12() { return PositiveTestString(Encoding.UTF8, "\u0130", new byte[] { 196, 176 }, "00L"); } public bool Test13() { return PositiveTestString(Encoding.UTF8, "\uDD75\uDD75\uD803\uDD75\uDD75\uDD75\uDD75\uD803\uD803\uD803\uDD75\uDD75\uDD75\uDD75", new byte[] { 239, 191, 189, 239, 191, 189, 240, 144, 181, 181, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 240, 144, 181, 181, 239, 191, 189, 239, 191, 189, 239, 191, 189 }, "0A2"); } public bool Test40() { return PositiveTestString(Encoding.Unicode, "TestString", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103, 0 }, "00A3"); } public bool Test41() { return PositiveTestString(Encoding.Unicode, "", new byte[] { }, "00B3"); } public bool Test42() { return PositiveTestString(Encoding.Unicode, "FooBA\u0400R", new byte[] { 70, 0, 111, 0, 111, 0, 66, 0, 65, 0, 0, 4, 82, 0 }, "00C3"); } public bool Test43() { return PositiveTestString(Encoding.Unicode, "\u00C0nima\u0300l", new byte[] { 192, 0, 110, 0, 105, 0, 109, 0, 97, 0, 0, 3, 108, 0 }, "00D3"); } public bool Test44() { return PositiveTestString(Encoding.Unicode, "Test\uD803\uDD75Test", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 3, 216, 117, 221, 84, 0, 101, 0, 115, 0, 116, 0 }, "00E3"); } public bool Test45() { return PositiveTestString(Encoding.Unicode, "Test\uD803Test", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 253, 255, 84, 0, 101, 0, 115, 0, 116, 0 }, "00F3"); } public bool Test46() { return PositiveTestString(Encoding.Unicode, "Test\uDD75Test", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 253, 255, 84, 0, 101, 0, 115, 0, 116, 0, }, "00G3"); } public bool Test47() { return PositiveTestString(Encoding.Unicode, "TestTest\uDD75", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 253, 255 }, "00H3"); } public bool Test48() { return PositiveTestString(Encoding.Unicode, "TestTest\uD803", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 253, 255 }, "00I3"); } public bool Test49() { return PositiveTestString(Encoding.Unicode, "\uDD75", new byte[] { 253, 255 }, "00J3"); } public bool Test50() { return PositiveTestString(Encoding.Unicode, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 3, 216, 117, 221, 3, 216, 117, 221, 3, 216, 117, 221 }, "00K3"); } public bool Test51() { return PositiveTestString(Encoding.Unicode, "\u0130", new byte[] { 48, 1 }, "00L3"); } public bool Test52() { return PositiveTestString(Encoding.Unicode, "\uDD75\uDD75\uD803\uDD75\uDD75\uDD75\uDD75\uD803\uD803\uD803\uDD75\uDD75\uDD75\uDD75", new byte[] { 253, 255, 253, 255, 3, 216, 117, 221, 253, 255, 253, 255, 253, 255, 253, 255, 253, 255, 3, 216, 117, 221, 253, 255, 253, 255, 253, 255 }, "0A23"); } public bool Test53() { return PositiveTestString(Encoding.BigEndianUnicode, "TestString", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103 }, "00A4"); } public bool Test54() { return PositiveTestString(Encoding.BigEndianUnicode, "", new byte[] { }, "00B4"); } public bool Test55() { return PositiveTestString(Encoding.BigEndianUnicode, "FooBA\u0400R", new byte[] { 0, 70, 0, 111, 0, 111, 0, 66, 0, 65, 4, 0, 0, 82 }, "00C4"); } public bool Test56() { return PositiveTestString(Encoding.BigEndianUnicode, "\u00C0nima\u0300l", new byte[] { 0, 192, 0, 110, 0, 105, 0, 109, 0, 97, 3, 0, 0, 108 }, "00D4"); } public bool Test57() { return PositiveTestString(Encoding.BigEndianUnicode, "Test\uD803\uDD75Test", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 216, 3, 221, 117, 0, 84, 0, 101, 0, 115, 0, 116 }, "00E4"); } public bool Test58() { return PositiveTestString(Encoding.BigEndianUnicode, "Test\uD803Test", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 255, 253, 0, 84, 0, 101, 0, 115, 0, 116 }, "00F4"); } public bool Test59() { return PositiveTestString(Encoding.BigEndianUnicode, "Test\uDD75Test", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 255, 253, 0, 84, 0, 101, 0, 115, 0, 116 }, "00G4"); } public bool Test60() { return PositiveTestString(Encoding.BigEndianUnicode, "TestTest\uDD75", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 255, 253 }, "00H4"); } public bool Test61() { return PositiveTestString(Encoding.BigEndianUnicode, "TestTest\uD803", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 255, 253 }, "00I4"); } public bool Test62() { return PositiveTestString(Encoding.BigEndianUnicode, "\uDD75", new byte[] { 255, 253 }, "00J4"); } public bool Test63() { return PositiveTestString(Encoding.BigEndianUnicode, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 216, 3, 221, 117, 216, 3, 221, 117, 216, 3, 221, 117 }, "00K4"); } public bool Test64() { return PositiveTestString(Encoding.BigEndianUnicode, "\u0130", new byte[] { 1, 48 }, "00L4"); } public bool Test65() { return PositiveTestString(Encoding.BigEndianUnicode, "\uDD75\uDD75\uD803\uDD75\uDD75\uDD75\uDD75\uD803\uD803\uD803\uDD75\uDD75\uDD75\uDD75", new byte[] { 255, 253, 255, 253, 216, 3, 221, 117, 255, 253, 255, 253, 255, 253, 255, 253, 255, 253, 216, 3, 221, 117, 255, 253, 255, 253, 255, 253 }, "0A24"); } public bool Test66() { return PositiveTestChars(Encoding.UTF8, new char[] { 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g' }, new byte[] { 84, 101, 115, 116, 83, 116, 114, 105, 110, 103 }, "00M"); } public bool Test69() { return PositiveTestChars(Encoding.Unicode, new char[] { 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g' }, new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103, 0 }, "00M3"); } public bool Test70() { return PositiveTestChars(Encoding.BigEndianUnicode, new char[] { 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g' }, new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103 }, "00M4"); } // Negative Tests public bool Test71() { return NegativeTestString(new UTF8Encoding(), null, typeof(ArgumentNullException), "00N"); } public bool Test74() { return NegativeTestString(new UnicodeEncoding(), null, typeof(ArgumentNullException), "00N3"); } public bool Test75() { return NegativeTestString(new UnicodeEncoding(true, false), null, typeof(ArgumentNullException), "00N4"); } public bool Test76() { return NegativeTestChars(new UTF8Encoding(), null, typeof(ArgumentNullException), "00O"); } public bool Test79() { return NegativeTestChars(new UnicodeEncoding(), null, typeof(ArgumentNullException), "00O3"); } public bool Test80() { return NegativeTestChars(new UnicodeEncoding(true, false), null, typeof(ArgumentNullException), "00O4"); } public bool Test81() { return NegativeTestChars2(new UTF8Encoding(), null, 0, 0, typeof(ArgumentNullException), "00P"); } public bool Test82() { return NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, -1, 1, typeof(ArgumentOutOfRangeException), "00P"); } public bool Test83() { return NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, 1, -1, typeof(ArgumentOutOfRangeException), "00Q"); } public bool Test84() { return NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, 0, 10, typeof(ArgumentOutOfRangeException), "00R"); } public bool Test85() { return NegativeTestChars2(new UTF8Encoding(), new char[] { 't' }, 2, 0, typeof(ArgumentOutOfRangeException), "00S"); } public bool Test96() { return NegativeTestChars2(new UnicodeEncoding(), null, 0, 0, typeof(ArgumentNullException), "00P3"); } public bool Test97() { return NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, -1, 1, typeof(ArgumentOutOfRangeException), "00P3"); } public bool Test98() { return NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, 1, -1, typeof(ArgumentOutOfRangeException), "00Q3"); } public bool Test99() { return NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, 0, 10, typeof(ArgumentOutOfRangeException), "00R3"); } public bool Test100() { return NegativeTestChars2(new UnicodeEncoding(), new char[] { 't' }, 2, 0, typeof(ArgumentOutOfRangeException), "00S3"); } public bool Test101() { return NegativeTestChars2(new UnicodeEncoding(true, false), null, 0, 0, typeof(ArgumentNullException), "00P4"); } public bool Test102() { return NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, -1, 1, typeof(ArgumentOutOfRangeException), "00P4"); } public bool Test103() { return NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, 1, -1, typeof(ArgumentOutOfRangeException), "00Q4"); } public bool Test104() { return NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, 0, 10, typeof(ArgumentOutOfRangeException), "00R4"); } public bool Test105() { return NegativeTestChars2(new UnicodeEncoding(true, false), new char[] { 't' }, 2, 0, typeof(ArgumentOutOfRangeException), "00S4"); } static byte[] output = new byte[20]; public bool Test106() { return NegativeTestChars3(Encoding.UTF8, null, 0, 0, output, 0, typeof(ArgumentNullException), "00T"); } public bool Test107() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, 0, null, 0, typeof(ArgumentNullException), "00U"); } public bool Test108() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00V"); } public bool Test109() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00W"); } public bool Test110() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00X"); } public bool Test111() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Y"); } public bool Test112() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Z"); } public bool Test113() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, 1, output, 20, typeof(ArgumentException), "0A0"); } public bool Test114() { return NegativeTestChars3(Encoding.UTF8, new char[] { 't' }, 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A1"); } public bool Test133() { return NegativeTestChars3(Encoding.Unicode, null, 0, 0, output, 0, typeof(ArgumentNullException), "00T3"); } public bool Test134() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, 0, null, 0, typeof(ArgumentNullException), "00U3"); } public bool Test135() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00V3"); } public bool Test136() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00W3"); } public bool Test137() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00X3"); } public bool Test138() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Y3"); } public bool Test139() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Z3"); } public bool Test140() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, 1, output, 20, typeof(ArgumentException), "0A03"); } public bool Test141() { return NegativeTestChars3(Encoding.Unicode, new char[] { 't' }, 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A13"); } public bool Test142() { return NegativeTestChars3(Encoding.BigEndianUnicode, null, 0, 0, output, 0, typeof(ArgumentNullException), "00T4"); } public bool Test143() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, 0, null, 0, typeof(ArgumentNullException), "00U4"); } public bool Test144() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00V4"); } public bool Test145() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00W4"); } public bool Test146() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00X4"); } public bool Test147() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Y4"); } public bool Test148() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Z4"); } public bool Test149() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, 1, output, 20, typeof(ArgumentException), "0A04"); } public bool Test150() { return NegativeTestChars3(Encoding.BigEndianUnicode, new char[] { 't' }, 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A14"); } public bool Test151() { return NegativeTestString1(Encoding.UTF8, null, 0, 0, output, 0, typeof(ArgumentNullException), "00Ta"); } public bool Test152() { return NegativeTestString1(Encoding.UTF8, "t", 0, 0, null, 0, typeof(ArgumentNullException), "00Ua"); } public bool Test153() { return NegativeTestString1(Encoding.UTF8, "t", -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00Va"); } public bool Test154() { return NegativeTestString1(Encoding.UTF8, "t", 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00Wa"); } public bool Test155() { return NegativeTestString1(Encoding.UTF8, "t", 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00Xa"); } public bool Test156() { return NegativeTestString1(Encoding.UTF8, "t", 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Ya"); } public bool Test157() { return NegativeTestString1(Encoding.UTF8, "t", 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Za"); } public bool Test158() { return NegativeTestString1(Encoding.UTF8, "t", 0, 1, output, 20, typeof(ArgumentException), "0A0a"); } public bool Test159() { return NegativeTestString1(Encoding.UTF8, "t", 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A1a"); } public bool Test178() { return NegativeTestString1(Encoding.Unicode, null, 0, 0, output, 0, typeof(ArgumentNullException), "00T3a"); } public bool Test179() { return NegativeTestString1(Encoding.Unicode, "t", 0, 0, null, 0, typeof(ArgumentNullException), "00U3a"); } public bool Test180() { return NegativeTestString1(Encoding.Unicode, "t", -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00V3a"); } public bool Test181() { return NegativeTestString1(Encoding.Unicode, "t", 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00W3a"); } public bool Test182() { return NegativeTestString1(Encoding.Unicode, "t", 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00X3a"); } public bool Test183() { return NegativeTestString1(Encoding.Unicode, "t", 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Y3a"); } public bool Test184() { return NegativeTestString1(Encoding.Unicode, "t", 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Z3a"); } public bool Test185() { return NegativeTestString1(Encoding.Unicode, "t", 0, 1, output, 20, typeof(ArgumentException), "0A03a"); } public bool Test186() { return NegativeTestString1(Encoding.Unicode, "t", 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A13a"); } public bool Test187() { return NegativeTestString1(Encoding.BigEndianUnicode, null, 0, 0, output, 0, typeof(ArgumentNullException), "00T4a"); } public bool Test188() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, 0, null, 0, typeof(ArgumentNullException), "00U4a"); } public bool Test189() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", -1, 0, output, 0, typeof(ArgumentOutOfRangeException), "00V4a"); } public bool Test190() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, 0, output, -1, typeof(ArgumentOutOfRangeException), "00W4a"); } public bool Test191() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 2, 0, output, 0, typeof(ArgumentOutOfRangeException), "00X4a"); } public bool Test192() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, 0, output, 21, typeof(ArgumentOutOfRangeException), "00Y4a"); } public bool Test193() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, 10, output, 0, typeof(ArgumentOutOfRangeException), "00Z4a"); } public bool Test194() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, 1, output, 20, typeof(ArgumentException), "0A04a"); } public bool Test195() { return NegativeTestString1(Encoding.BigEndianUnicode, "t", 0, -1, output, 0, typeof(ArgumentOutOfRangeException), "0A14a"); } public bool PositiveTestString(Encoding enc, string str, byte[] expected, string id) { bool result = true; TestFramework.BeginScenario(id + ": Getting bytes for " + str + " with encoding " + enc.WebName); try { byte[] bytes = enc.GetBytes(str); if (!Utilities.CompareBytes(bytes, expected)) { result = false; TestFramework.LogError("001", "Error in " + id + ", unexpected comparison result. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", Expected: " + Utilities.ByteArrayToString(expected)); } } catch (Exception exc) { result = false; TestFramework.LogError("002", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool NegativeTestString(Encoding enc, string str, Type excType, string id) { bool result = true; TestFramework.BeginScenario(id + ": Getting bytes with encoding " + enc.WebName); try { byte[] bytes = enc.GetBytes(str); result = false; TestFramework.LogError("005", "Error in " + id + ", Expected exception not thrown. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", Expected exception type: " + excType.ToString()); } catch (Exception exc) { if (exc.GetType() != excType) { result = false; TestFramework.LogError("006", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } } return result; } public bool PositiveTestChars(Encoding enc, char[] chars, byte[] expected, string id) { bool result = true; TestFramework.BeginScenario(id + ": Getting bytes for " + new string(chars) + " with encoding " + enc.WebName); try { byte[] bytes = enc.GetBytes(chars); if (!Utilities.CompareBytes(bytes, expected)) { result = false; TestFramework.LogError("003", "Error in " + id + ", unexpected comparison result. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", Expected: " + Utilities.ByteArrayToString(expected)); } } catch (Exception exc) { result = false; TestFramework.LogError("004", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool NegativeTestChars(Encoding enc, char[] str, Type excType, string id) { bool result = true; TestFramework.BeginScenario(id + ": Getting bytes with encoding " + enc.WebName); try { byte[] bytes = enc.GetBytes(str); result = false; TestFramework.LogError("007", "Error in " + id + ", Expected exception not thrown. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", Expected exception type: " + excType.ToString()); } catch (Exception exc) { if (exc.GetType() != excType) { result = false; TestFramework.LogError("008", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } } return result; } public bool NegativeTestChars2(Encoding enc, char[] str, int index, int count, Type excType, string id) { bool result = true; TestFramework.BeginScenario(id + ": Getting bytes with encoding " + enc.WebName); try { byte[] bytes = enc.GetBytes(str, index, count); result = false; TestFramework.LogError("009", "Error in " + id + ", Expected exception not thrown. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", Expected exception type: " + excType.ToString()); } catch (Exception exc) { if (exc.GetType() != excType) { result = false; TestFramework.LogError("010", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } } return result; } public bool NegativeTestChars3(Encoding enc, char[] str, int index, int count, byte[] bytes, int bIndex, Type excType, string id) { bool result = true; TestFramework.BeginScenario(id + ": Getting bytes with encoding " + enc.WebName); try { int output = enc.GetBytes(str, index, count, bytes, bIndex); result = false; TestFramework.LogError("011", "Error in " + id + ", Expected exception not thrown. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", Expected exception type: " + excType.ToString()); } catch (Exception exc) { if (exc.GetType() != excType) { result = false; TestFramework.LogError("012", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } } return result; } public bool NegativeTestString1(Encoding enc, string str, int index, int count, byte[] bytes, int bIndex, Type excType, string id) { bool result = true; TestFramework.BeginScenario(id + ": Getting bytes with encoding " + enc.WebName); try { int output = enc.GetBytes(str, index, count, bytes, bIndex); result = false; TestFramework.LogError("013", "Error in " + id + ", Expected exception not thrown. Actual bytes " + Utilities.ByteArrayToString(bytes) + ", Expected exception type: " + excType.ToString()); } catch (Exception exc) { if (exc.GetType() != excType) { result = false; TestFramework.LogError("014", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } } 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.Collections.Generic; using System.Security; using Xunit; namespace System.Reflection.Tests { public class GetCustomAttributes_MemberInfo { private static readonly Type s_typeWithoutAttr = typeof(TestClassWithoutAttribute); private static readonly Type s_typeBaseClass = typeof(TestBaseClass); private static readonly Type s_typeTestClass = typeof(TestClass); [Fact] public void IsDefined_Inherit() { Assert.False(CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_Single_Inherited), false)); } [Fact] public void IsDefined() { Assert.True(CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_Single_M))); AssertExtensions.Throws<ArgumentException>(null, () => { CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), typeof(string)); }); Assert.Throws<ArgumentNullException>(() => { CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), null); }); } [Fact] public void GetCustomAttributeOfT_Single_NotInherited() { Attribute attribute = CustomAttributeExtensions.GetCustomAttribute<MyAttribute_Single_Inherited>(s_typeTestClass.GetTypeInfo(), false); Assert.Null(attribute); } [Fact] public void GetCustomAttributeOfT_Single() { Attribute attribute = CustomAttributeExtensions.GetCustomAttribute<MyAttribute_Single_Inherited>(s_typeTestClass.GetTypeInfo()); Assert.NotNull(attribute); Assert.Throws<AmbiguousMatchException>(() => { attribute = CustomAttributeExtensions.GetCustomAttribute<MyAttribute_AllowMultiple_Inherited>(s_typeTestClass.GetTypeInfo()); }); } [Fact] public void GetCustomAttributeT_Multiple_NoInheirit() { var attributes = CustomAttributeExtensions.GetCustomAttributes<MyAttribute_AllowMultiple_Inherited>(s_typeTestClass.GetTypeInfo(), false); Assert.Equal(1, attributes.Count()); } [Fact] public void GetCustomAttributeOfT_Multiple() { IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes<MyAttribute_Single_Inherited>(s_typeTestClass.GetTypeInfo()); Assert.Equal(1, attributes.Count()); attributes = CustomAttributeExtensions.GetCustomAttributes<SecurityCriticalAttribute>(s_typeTestClass.GetTypeInfo()); Assert.Equal(0, attributes.Count()); } [Fact] public void GetCustomAttribute_Multiple_NotInherited() { var attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited), false); Assert.NotNull(attribute); var attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited), false); Assert.Equal(1, attributes.Count()); } [Fact] public void GetCustomAttributeSingle() { Attribute attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_Single_M)); Assert.NotNull(attribute); Assert.Throws<AmbiguousMatchException>(() => { attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited)); }); AssertExtensions.Throws<ArgumentException>(null, () => { attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(string)); }); Assert.Throws<ArgumentNullException>(() => { attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), null); }); } [Fact] public void GetCustomAttribute4() { IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited)); Assert.Equal(2, attributes.Count()); attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(SecurityCriticalAttribute)); Assert.Equal(0, attributes.Count()); AssertExtensions.Throws<ArgumentException>(null, () => { attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(string)); }); Assert.Throws<ArgumentNullException>(() => { attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), null); }); } [Fact] public void GetCustomAttribute5() { IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), false); Assert.Equal(4, attributes.Count()); Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_Single_M single", StringComparison.Ordinal))); Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple1", StringComparison.Ordinal))); Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple2", StringComparison.Ordinal))); Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_Inherited multiple", StringComparison.Ordinal))); } [Fact] public void GetCustomAttributeAll() { IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeWithoutAttr.GetTypeInfo()); Assert.Equal(0, attributes.Count()); attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), true); IEnumerator<Attribute> customAttrs = attributes.GetEnumerator(); Assert.Equal(6, attributes.Count()); Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_Single_M single", StringComparison.Ordinal))); Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple1", StringComparison.Ordinal))); Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple2", StringComparison.Ordinal))); Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_Single_Inherited singleBase", StringComparison.Ordinal))); Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_Inherited multiple", StringComparison.Ordinal))); Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_Inherited multipleBase", StringComparison.Ordinal))); IEnumerable<CustomAttributeData> attributeData = s_typeTestClass.GetTypeInfo().CustomAttributes; IEnumerator<CustomAttributeData> customAttrsdata = attributeData.GetEnumerator(); Assert.Equal(4, attributeData.Count()); Assert.Equal(3, attributeData.Count(attr => attr.ToString().Contains("MyAttribute_AllowMultiple"))); Assert.Equal(1, attributeData.Count(attr => attr.ToString().Contains("MyAttribute_Single_M"))); } } public class MyAttributeBase_M : Attribute { private string _name; public MyAttributeBase_M(string name) { _name = name; } public override string ToString() { return this.GetType() + " " + _name; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class MyAttribute_Single_M : MyAttributeBase_M { public MyAttribute_Single_M(string name) : base(name) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class MyAttribute_AllowMultiple_M : MyAttributeBase_M { public MyAttribute_AllowMultiple_M(string name) : base(name) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] public class MyAttribute_Single_Inherited : MyAttributeBase_M { public MyAttribute_Single_Inherited(string name) : base(name) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)] public class MyAttribute_AllowMultiple_Inherited : MyAttributeBase_M { public MyAttribute_AllowMultiple_Inherited(string name) : base(name) { } } public class TestClassWithoutAttribute { } [MyAttribute_Single_M("singleBase"), MyAttribute_AllowMultiple_M("multiple1Base"), MyAttribute_AllowMultiple_M("multiple2Base"), MyAttribute_Single_Inherited("singleBase"), MyAttribute_AllowMultiple_Inherited("multipleBase")] public class TestBaseClass { } [MyAttribute_Single_M("single"), MyAttribute_AllowMultiple_M("multiple1"), MyAttribute_AllowMultiple_M("multiple2"), MyAttribute_AllowMultiple_Inherited("multiple")] public class TestClass : TestBaseClass { } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Originally based on the Bartok code base. // using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace Microsoft.Zelig.MetaData.Importer { public partial class MetaDataMethod : MetaDataObject { // Internal Types private enum MethodFormats : byte { Tiny = 2, Fat = 3, Tiny1 = 6 } private enum SectionKind : byte { Reserved = 0, EHTable = 1, OptILTable = 2 } private static readonly EHClause[] s_sharedEmptyTable = new EHClause[0]; // // Constructor Methods // private void getInstructions( Parser mdParser , PdbInfo.PdbFunction pdbFunction ) { ArrayReader reader = mdParser.ImageReaderAtVirtualAddress( m_rva ); byte headerByte = reader.ReadUInt8(); byte formatMask = (byte)(headerByte & 0x7); int codeSize; ArrayReader codeReader; m_ehTable = s_sharedEmptyTable; switch((MethodFormats)formatMask) { case MethodFormats.Tiny: case MethodFormats.Tiny1: { m_initLocals = false; m_maxStack = 8; m_locals = null; codeSize = headerByte >> 2; codeReader = reader.CreateSubsetAndAdvance( codeSize ); break; } case MethodFormats.Fat: { // // for Fat format, check for CorILMethod_InitLocals // Section 25.4.3 of ECMA spec, Partition II // m_initLocals = ((headerByte & 0x10) != 0); byte headerByte2 = reader.ReadUInt8(); int size = headerByte2 >> 4; if(size != 3) { throw new IllegalInstructionStreamException( "Unexpected FAT size: " + size ); } m_maxStack = reader.ReadUInt16(); codeSize = reader.ReadInt32(); int localVarSignatureToken = reader.ReadInt32(); if(localVarSignatureToken == 0) { m_locals = null; } else { MetaDataStandAloneSig standAloneSig = (MetaDataStandAloneSig)mdParser.getObjectFromToken( localVarSignatureToken ); SignatureLocalVar localVarSignature = (SignatureLocalVar)standAloneSig.Signature; m_locals = localVarSignature.Locals; } codeReader = reader.CreateSubsetAndAdvance( codeSize ); break; } default: { throw new IllegalInstructionStreamException( "Unknown format: " + formatMask.ToString( "x" ) ); } } int[] byteToInstrMapping = new int[codeSize + 1]; int instructionCount = 0; while(true) { byteToInstrMapping[codeReader.Position] = instructionCount; if(codeReader.Position >= codeSize) break; instructionCount++; Normalized.Instruction.Opcode opcode = (Normalized.Instruction.Opcode)codeReader.ReadUInt8(); switch(opcode) { case Normalized.Instruction.Opcode.PREFIX1: opcode = (Normalized.Instruction.Opcode)((int)codeReader.ReadUInt8() + 256); if(opcode < 0 || (Normalized.Instruction.Opcode)opcode >= Normalized.Instruction.Opcode.COUNT) { throw new IllegalInstructionStreamException( "Saw prefixed opcode of " + opcode ); } break; case Normalized.Instruction.Opcode.PREFIXREF: case Normalized.Instruction.Opcode.PREFIX2: case Normalized.Instruction.Opcode.PREFIX3: case Normalized.Instruction.Opcode.PREFIX4: case Normalized.Instruction.Opcode.PREFIX5: case Normalized.Instruction.Opcode.PREFIX6: case Normalized.Instruction.Opcode.PREFIX7: throw new IllegalInstructionStreamException( "Saw unexpected prefix opcode " + opcode ); } Normalized.Instruction.OpcodeInfo opcodeInfo = Normalized.Instruction.OpcodeInfoTable[(int)opcode]; int operandSize = opcodeInfo.OperandSize; if(operandSize == -1) { switch(opcodeInfo.OperandFormat) { case Normalized.Instruction.OpcodeOperand.Switch: { int caseCount = codeReader.ReadInt32(); codeReader.Seek( 4 * caseCount ); break; } } } else { codeReader.Seek( operandSize ); } } //--// // Check whether or not there is an EH section if(formatMask == (byte)MethodFormats.Fat && (headerByte & 0x08) != 0) { int sectionPadding = (m_rva + codeSize) % 4; if(sectionPadding != 0) { while(sectionPadding < 4) { sectionPadding++; byte padding = reader.ReadUInt8(); } } byte sectionKind = reader.ReadUInt8(); if((sectionKind & 0x80) != 0) { throw new IllegalInstructionStreamException( "More than one section after the code" ); } if((sectionKind & 0x3F) != (int)SectionKind.EHTable) { throw new IllegalInstructionStreamException( "Expected EH table section, got " + sectionKind.ToString( "x" ) ); } //--// bool smallSection = ((sectionKind & 0x40) == 0); int dataSize; if(smallSection) { // Small section int ehByteCount = reader.ReadUInt8(); switch((ehByteCount % 12)) { case 0: // Some compilers generate the wrong value here, they forget to add the size of the header. case 4: break; default: throw new IllegalInstructionStreamException( "Unexpected byte count for small EH table: " + ehByteCount ); } int sectSmallReserved = reader.ReadInt16(); dataSize = (ehByteCount) / 12; } else { // Fat section int ehByteCount; ehByteCount = reader.ReadUInt8(); ehByteCount |= reader.ReadUInt8() << 8; ehByteCount |= reader.ReadUInt8() << 16; switch((ehByteCount % 24)) { case 0: // Some compilers generate the wrong value here, they forget to add the size of the header. case 4: break; default: throw new IllegalInstructionStreamException( "Unexpected byte count for fat EH table: " + ehByteCount ); } dataSize = ehByteCount / 24; } m_ehTable = new EHClause[dataSize]; for(int i = 0; i < dataSize; i++) { int flags; int tryOffset; int tryLength; int handlerOffset; int handlerLength; int tokenOrOffset; if(smallSection) { flags = reader.ReadUInt16(); tryOffset = reader.ReadUInt16(); tryLength = reader.ReadUInt8(); handlerOffset = reader.ReadUInt16(); handlerLength = reader.ReadUInt8(); tokenOrOffset = reader.ReadInt32(); } else { flags = reader.ReadInt32(); tryOffset = reader.ReadInt32(); tryLength = reader.ReadInt32(); handlerOffset = reader.ReadInt32(); handlerLength = reader.ReadInt32(); tokenOrOffset = reader.ReadInt32(); } int tryInstrOffset = byteToInstrMapping[tryOffset ]; int tryInstrEnd = byteToInstrMapping[tryOffset + tryLength ]; int handlerInstrOffset = byteToInstrMapping[handlerOffset ]; int handlerInstrEnd = byteToInstrMapping[handlerOffset + handlerLength]; IMetaDataTypeDefOrRef classObject = null; if((flags & (int)EHClause.ExceptionFlag.Filter) != 0) { tokenOrOffset = byteToInstrMapping[tokenOrOffset]; } else if(flags == (int)EHClause.ExceptionFlag.None) { classObject = (IMetaDataTypeDefOrRef)mdParser.getObjectFromToken( tokenOrOffset ); tokenOrOffset = 0; } else { // // Managed C++ emits finally blocks with a token. So we cannot enforce this check. // //if(MetaData.UnpackTokenAsIndex( tokenOrOffset ) != 0) //{ // throw new IllegalInstructionStreamException( "Unknown token or offset " + tokenOrOffset.ToString( "x8" ) ); //} } m_ehTable[i] = new EHClause( flags , tryInstrOffset , tryInstrEnd - tryInstrOffset , handlerInstrOffset , handlerInstrEnd - handlerInstrOffset , tokenOrOffset , classObject ); } } m_instructions = new Instruction[instructionCount]; int instructionCounter = 0; Debugging.DebugInfo debugInfo = null; codeReader.Rewind(); while(codeReader.Position < codeSize) { int pc = codeReader.Position; if(pc > 0 && byteToInstrMapping[pc] == 0) { throw new IllegalInstructionStreamException( "Out of sync at " + pc.ToString( "x" ) ); } Normalized.Instruction.Opcode opcode = (Normalized.Instruction.Opcode)codeReader.ReadUInt8(); if(opcode == Normalized.Instruction.Opcode.PREFIX1) { opcode = (Normalized.Instruction.Opcode)((int)codeReader.ReadUInt8() + 256); } Normalized.Instruction.OpcodeInfo opcodeInfo = Normalized.Instruction.OpcodeInfoTable[(int)opcode]; int operandSize = opcodeInfo.OperandSize; Instruction.Operand operand; switch(opcodeInfo.OperandFormat) { case Normalized.Instruction.OpcodeOperand.None: operand = null; break; case Normalized.Instruction.OpcodeOperand.Var: operand = new Instruction.OperandInt( (int)ReadOperandUInt( opcodeInfo, codeReader ) ); break; case Normalized.Instruction.OpcodeOperand.Int: if(operandSize == 8) { operand = new Instruction.OperandLong( codeReader.ReadInt64() ); } else { operand = new Instruction.OperandInt( ReadOperandInt( opcodeInfo, codeReader ) ); } break; case Normalized.Instruction.OpcodeOperand.Float: if(operandSize == 8) { operand = new Instruction.OperandDouble( codeReader.ReadDouble() ); } else { operand = new Instruction.OperandSingle( codeReader.ReadSingle() ); } break; case Normalized.Instruction.OpcodeOperand.Branch: { int target = ReadOperandInt( opcodeInfo, codeReader ); int instrTarget = byteToInstrMapping[codeReader.Position + target]; operand = new Instruction.OperandTarget( instrTarget ); break; } case Normalized.Instruction.OpcodeOperand.Method: { int token = codeReader.ReadInt32(); MetaDataObject mdMethod = mdParser.getObjectFromToken( token ); operand = new Instruction.OperandObject( mdMethod ); break; } case Normalized.Instruction.OpcodeOperand.Field: { int token = codeReader.ReadInt32(); MetaDataObject mdField = mdParser.getObjectFromToken( token ); operand = new Instruction.OperandObject( mdField ); break; } case Normalized.Instruction.OpcodeOperand.Type: { int token = codeReader.ReadInt32(); MetaDataObject type = mdParser.getObjectFromToken( token ); operand = new Instruction.OperandObject( type ); break; } case Normalized.Instruction.OpcodeOperand.Token: { int token = codeReader.ReadInt32(); MetaDataObject mdToken = mdParser.getObjectFromToken( token ); operand = new Instruction.OperandObject( mdToken ); break; } case Normalized.Instruction.OpcodeOperand.String: { int token = codeReader.ReadInt32(); if(MetaData.UnpackTokenAsType( token ) != TokenType.String) { throw new IllegalInstructionStreamException( "Unexpected string token " + token.ToString( "x" ) ); } int index = MetaData.UnpackTokenAsIndex( token ); operand = new Instruction.OperandString( mdParser.getUserString( index ) ); break; } case Normalized.Instruction.OpcodeOperand.Sig: { int token = codeReader.ReadInt32(); MetaDataObject calleeDescr = mdParser.getObjectFromToken( token ); operand = new Instruction.OperandObject( calleeDescr ); break; } case Normalized.Instruction.OpcodeOperand.Switch: { int caseCount = codeReader.ReadInt32(); int[] branchArray = new int[caseCount]; int nextPC = codeReader.Position + 4 * caseCount; for(int j = 0; j < caseCount; j++) { int target = codeReader.ReadInt32(); int instrTarget = byteToInstrMapping[nextPC + target]; branchArray[j] = instrTarget; } operand = new Instruction.OperandTargetArray( branchArray ); break; } default: throw new IllegalInstructionStreamException( "Invalid opcode " + opcodeInfo ); } // read in the line number information. PdbInfo.PdbSource file; PdbInfo.PdbLine line; if(pdbFunction != null && pdbFunction.FindOffset( (uint)pc, out file, out line )) { if(line.LineBegin != 0xFEEFEE) { debugInfo = new Debugging.DebugInfo( file.Name, (int)line.LineBegin, (int)line.ColumnBegin, (int)line.LineEnd, (int)line.ColumnEnd ); } else { // No debugging info. } } m_instructions[instructionCounter] = new Instruction( opcodeInfo, operand, debugInfo ); instructionCounter++; } } private static int ReadOperandInt( Normalized.Instruction.OpcodeInfo opcodeInfo, ArrayReader codeReader ) { switch(opcodeInfo.OperandSize) { case 0: return opcodeInfo.ImplicitOperandValue; case 1: return codeReader.ReadInt8(); case 2: return codeReader.ReadInt16(); case 4: return codeReader.ReadInt32(); } throw new IllegalInstructionStreamException( "Unknown operand size " + opcodeInfo.OperandSize ); } private static uint ReadOperandUInt( Normalized.Instruction.OpcodeInfo opcodeInfo, ArrayReader codeReader ) { switch(opcodeInfo.OperandSize) { case 0: return (uint)opcodeInfo.ImplicitOperandValue; case 1: return codeReader.ReadUInt8 (); case 2: return codeReader.ReadUInt16(); case 4: return codeReader.ReadUInt32(); } throw new IllegalInstructionStreamException( "Unknown operand size " + opcodeInfo.OperandSize ); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Internal classes public class IllegalInstructionStreamException : Exception { // // Constructor Methods // internal IllegalInstructionStreamException( String message ) : base( message ) { } } } }
namespace HomeCinema.Data.Migrations { using Entities; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<HomeCinema.Data.HomeCinemaContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(HomeCinemaContext context) { // create genres context.GenreSet.AddOrUpdate(g => g.Name, GenerateGenres()); // create movies context.MovieSet.AddOrUpdate(m => m.Title, GenerateMovies()); //// create stocks context.StockSet.AddOrUpdate(GenerateStocks()); // create customers context.CustomerSet.AddOrUpdate(GenerateCustomers()); // create roles context.RoleSet.AddOrUpdate(r => r.Name, GenerateRoles()); // username: chsakell, password: homecinema context.UserSet.AddOrUpdate(u => u.Email, new User[]{ new User() { Email="chsakells.blog@gmail.com", Username="chsakell", HashedPassword ="XwAQoiq84p1RUzhAyPfaMDKVgSwnn80NCtsE8dNv3XI=", Salt = "mNKLRbEFCH8y1xIyTXP4qA==", IsLocked = false, DateCreated = DateTime.Now, //Roles = new List<Role>() { new Role() { Id = 1 } } } }); // // create user-admin for chsakell //context.UserRoleSet.AddOrUpdate(new UserRole[] { // new UserRole() { // RoleId = 1, // admin // UserId = 1 // chsakell // } //}); } private Genre[] GenerateGenres() { Genre[] genres = new Genre[] { new Genre() { Name = "Comedy" }, new Genre() { Name = "Sci-fi" }, new Genre() { Name = "Action" }, new Genre() { Name = "Horror" }, new Genre() { Name = "Romance" }, new Genre() { Name = "Comedy" }, new Genre() { Name = "Crime" }, }; return genres; } private Movie[] GenerateMovies() { Movie[] movies = new Movie[] { new Movie() { Title="Minions", Image ="minions.jpg", GenreId = 1, Director ="Kyle Bald", Writer="Brian Lynch", Producer="Janet Healy", ReleaseDate = new DateTime(2015, 7, 10), Rating = 3, Description = "Minions Stuart, Kevin and Bob are recruited by Scarlet Overkill, a super-villain who, alongside her inventor husband Herb, hatches a plot to take over the world.", TrailerURI = "https://www.youtube.com/watch?v=Wfql_DoHRKc" }, new Movie() { Title="Ted 2", Image ="ted2.jpg", GenreId = 1, Director ="Seth MacFarlane", Writer="Seth MacFarlane", Producer="Jason Clark", ReleaseDate = new DateTime(2015, 6, 27), Rating = 4, Description = "Newlywed couple Ted and Tami-Lynn want to have a baby, but in order to qualify to be a parent, Ted will have to prove he's a person in a court of law.", TrailerURI = "https://www.youtube.com/watch?v=S3AVcCggRnU" }, new Movie() { Title="Trainwreck", Image ="trainwreck.jpg", GenreId = 2, Director ="Judd Apatow", Writer="Amy Schumer", Producer="Judd Apatow", ReleaseDate = new DateTime(2015, 7, 17), Rating = 5, Description = "Having thought that monogamy was never possible, a commitment-phobic career woman may have to face her fears when she meets a good guy.", TrailerURI = "https://www.youtube.com/watch?v=2MxnhBPoIx4" }, new Movie() { Title="Inside Out", Image ="insideout.jpg", GenreId = 1, Director ="Pete Docter", Writer="Pete Docter", Producer="John Lasseter", ReleaseDate = new DateTime(2015, 6, 19), Rating = 4, Description = "After young Riley is uprooted from her Midwest life and moved to San Francisco, her emotions - Joy, Fear, Anger, Disgust and Sadness - conflict on how best to navigate a new city, house, and school.", TrailerURI = "https://www.youtube.com/watch?v=seMwpP0yeu4" }, new Movie() { Title="Home", Image ="home.jpg", GenreId = 1, Director ="Tim Johnson", Writer="Tom J. Astle", Producer="Suzanne Buirgy", ReleaseDate = new DateTime(2015, 5, 27), Rating = 4, Description = "Oh, an alien on the run from his own people, lands on Earth and makes friends with the adventurous Tip, who is on a quest of her own.", TrailerURI = "https://www.youtube.com/watch?v=MyqZf8LiWvM" }, new Movie() { Title="Batman v Superman: Dawn of Justice", Image ="batmanvssuperman.jpg", GenreId = 2, Director ="Zack Snyder", Writer="Chris Terrio", Producer="Wesley Coller", ReleaseDate = new DateTime(2015, 3, 25), Rating = 4, Description = "Fearing the actions of a god-like Super Hero left unchecked, Gotham City's own formidable, forceful vigilante takes on Metropolis most revered, modern-day savior, while the world wrestles with what sort of hero it really needs. And with Batman and Superman at war with one another, a new threat quickly arises, putting mankind in greater danger than it's ever known before.", TrailerURI = "https://www.youtube.com/watch?v=0WWzgGyAH6Y" }, new Movie() { Title="Ant-Man", Image ="antman.jpg", GenreId = 2, Director ="Payton Reed", Writer="Edgar Wright", Producer="Victoria Alonso", ReleaseDate = new DateTime(2015, 7, 17), Rating = 5, Description = "Armed with a super-suit with the astonishing ability to shrink in scale but increase in strength, cat burglar Scott Lang must embrace his inner hero and help his mentor, Dr. Hank Pym, plan and pull off a heist that will save the world.", TrailerURI = "https://www.youtube.com/watch?v=1HpZevFifuo" }, new Movie() { Title="Jurassic World", Image ="jurassicworld.jpg", GenreId = 2, Director ="Colin Trevorrow", Writer="Rick Jaffa", Producer="Patrick Crowley", ReleaseDate = new DateTime(2015, 6, 12), Rating = 4, Description = "A new theme park is built on the original site of Jurassic Park. Everything is going well until the park's newest attraction--a genetically modified giant stealth killing machine--escapes containment and goes on a killing spree.", TrailerURI = "https://www.youtube.com/watch?v=RFinNxS5KN4" }, new Movie() { Title="Fantastic Four", Image ="fantasticfour.jpg", GenreId = 2, Director ="Josh Trank", Writer="Simon Kinberg", Producer="Avi Arad", ReleaseDate = new DateTime(2015, 8, 7), Rating = 2, Description = "Four young outsiders teleport to an alternate and dangerous universe which alters their physical form in shocking ways. The four must learn to harness their new abilities and work together to save Earth from a former friend turned enemy.", TrailerURI = "https://www.youtube.com/watch?v=AAgnQdiZFsQ" }, new Movie() { Title="Mad Max: Fury Road", Image ="madmax.jpg", GenreId = 2, Director ="George Miller", Writer="George Miller", Producer="Bruce Berman", ReleaseDate = new DateTime(2015, 5, 15), Rating = 3, Description = "In a stark desert landscape where humanity is broken, two rebels just might be able to restore order: Max, a man of action and of few words, and Furiosa, a woman of action who is looking to make it back to her childhood homeland.", TrailerURI = "https://www.youtube.com/watch?v=hEJnMQG9ev8" }, new Movie() { Title="True Detective", Image ="truedetective.jpg", GenreId = 6, Director ="Nic Pizzolatto", Writer="Bill Bannerman", Producer="Richard Brown", ReleaseDate = new DateTime(2015, 5, 15), Rating = 4, Description = "An anthology series in which police investigations unearth the personal and professional secrets of those involved, both within and outside the law.", TrailerURI = "https://www.youtube.com/watch?v=TXwCoNwBSkQ" }, new Movie() { Title="The Longest Ride", Image ="thelongestride.jpg", GenreId = 5, Director ="Nic Pizzolatto", Writer="George Tillman Jr.", Producer="Marty Bowen", ReleaseDate = new DateTime(2015, 5, 15), Rating = 5, Description = "After an automobile crash, the lives of a young couple intertwine with a much older man, as he reflects back on a past love.", TrailerURI = "https://www.youtube.com/watch?v=FUS_Q7FsfqU" }, new Movie() { Title="The Walking Dead", Image ="thewalkingdead.jpg", GenreId = 4, Director ="Frank Darabont", Writer="David Alpert", Producer="Gale Anne Hurd", ReleaseDate = new DateTime(2015, 3, 28), Rating = 5, Description = "Sheriff's Deputy Rick Grimes leads a group of survivors in a world overrun by zombies.", TrailerURI = "https://www.youtube.com/watch?v=R1v0uFms68U" }, new Movie() { Title="Southpaw", Image ="southpaw.jpg", GenreId = 3, Director ="Antoine Fuqua", Writer="Kurt Sutter", Producer="Todd Black", ReleaseDate = new DateTime(2015, 8, 17), Rating = 4, Description = "Boxer Billy Hope turns to trainer Tick Willis to help him get his life back on track after losing his wife in a tragic accident and his daughter to child protection services.", TrailerURI = "https://www.youtube.com/watch?v=Mh2ebPxhoLs" }, new Movie() { Title="Specter", Image ="spectre.jpg", GenreId = 3, Director ="Sam Mendes", Writer="Ian Fleming", Producer="Zakaria Alaoui", ReleaseDate = new DateTime(2015, 11, 5), Rating = 5, Description = "A cryptic message from Bond's past sends him on a trail to uncover a sinister organization. While M battles political forces to keep the secret service alive, Bond peels back the layers of deceit to reveal the terrible truth behind SPECTRE.", TrailerURI = "https://www.youtube.com/watch?v=LTDaET-JweU" }, }; return movies; } private Stock[] GenerateStocks() { List<Stock> stocks = new List<Stock>(); for (int i = 1; i <= 15; i++) { // Three stocks for each movie for (int j = 0; j < 3; j++) { Stock stock = new Stock() { MovieId = i, UniqueKey = Guid.NewGuid(), IsAvailable = true }; stocks.Add(stock); } } return stocks.ToArray(); } private Customer[] GenerateCustomers() { List<Customer> _customers = new List<Customer>(); // Create 100 customers for (int i = 0; i < 100; i++) { Customer customer = new Customer() { FirstName = MockData.Person.FirstName(), LastName = MockData.Person.Surname(), IdentityCard = Guid.NewGuid().ToString(), UniqueKey = Guid.NewGuid(), Email = MockData.Internet.Email(), DateOfBirth = new DateTime(1985, 10, 20).AddMonths(i).AddDays(10), RegistrationDate = DateTime.Now.AddDays(i), Mobile = "1234567890" }; _customers.Add(customer); } return _customers.ToArray(); } private Role[] GenerateRoles() { Role[] _roles = new Role[]{ new Role() { Name="Admin" } }; return _roles; } /*private Rental[] GenerateRentals() { for (int i = 1; i <= 45; i++) { for (int j = 1; j <= 5; j++) { Random r = new Random(); int customerId = r.Next(1, 99); Rental _rental = new Rental() { CustomerId = 1, StockId = 1, Status = "Returned", RentalDate = DateTime.Now.AddDays(j), ReturnedDate = DateTime.Now.AddDays(j + 1) }; _rentals.Add(_rental); } } //return _rentals.ToArray(); }*/ } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; namespace OpenLiveWriter.Controls { public partial class ImageCropControl : UserControl { private const AnchorStyles ANCHOR_ALL = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right; private Bitmap bitmap; private DualRects crop; private CachedResizedBitmap crbNormal; private CachedResizedBitmap crbGrayed; private bool gridLines; private CropStrategy cropStrategy = new FreeCropStrategy(); private bool fireCropChangedOnKeyUp = false; public ImageCropControl() { SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.ResizeRedraw, true); InitializeComponent(); AccessibleRole = AccessibleRole.Pane; TabStop = true; } public bool GridLines { get { return gridLines; } set { if (gridLines != value) { gridLines = value; Invalidate(); } } } public event EventHandler CropRectangleChanged; private void OnCropRectangleChanged() { CropRectangleChanged?.Invoke(this, EventArgs.Empty); } public event EventHandler AspectRatioChanged; private void OnAspectRatioChanged() { AspectRatioChanged?.Invoke(this, EventArgs.Empty); } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Rectangle CropRectangle { get { return crop.Real; } set { crop.Real = value; } } public void Crop() { Bitmap newBitmap = new Bitmap(bitmap, crop.Real.Size.Width, crop.Real.Size.Height); using (Graphics g = Graphics.FromImage(newBitmap)) { g.CompositingMode = CompositingMode.SourceCopy; g.DrawImage(bitmap, new Rectangle(0, 0, newBitmap.Width, newBitmap.Height), crop.Real, GraphicsUnit.Pixel); } Bitmap = newBitmap; } public double? AspectRatio { get { return cropStrategy.AspectRatio; } set { if (value == null) { cropStrategy = new FreeCropStrategy(); OnAspectRatioChanged(); Invalidate(); } else { cropStrategy = new FixedAspectRatioCropStrategy(value.Value); OnAspectRatioChanged(); Rectangle containerRect = crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height); Rectangle cropped = ((FixedAspectRatioCropStrategy)cropStrategy).ConformCropRectangle(containerRect, crop.Virtual); if (cropped.Right > containerRect.Right) cropped.X -= cropped.Right - containerRect.Right; if (cropped.Bottom > containerRect.Bottom) cropped.Y -= cropped.Bottom - containerRect.Bottom; if (cropped.Left < containerRect.Left) cropped.X += containerRect.Left - cropped.Left; if (cropped.Top < containerRect.Top) cropped.Y += containerRect.Top - cropped.Top; crop.Virtual = cropped; if (!cropStrategy.IsDragging) { cropStrategy.BeginDrag( crop.Virtual, new Point(crop.Virtual.Right, crop.Virtual.Bottom), AnchorStyles.Bottom | AnchorStyles.Right, crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height)); crop.Virtual = cropStrategy.GetNewBounds(new Point(crop.Virtual.Right, crop.Virtual.Bottom)); Invalidate(); Update(); OnCropRectangleChanged(); cropStrategy.EndDrag(); } } } } private void NullAndDispose<T>(ref T disposable) where T : IDisposable { IDisposable tmp = disposable; disposable = default(T); if (tmp != null) tmp.Dispose(); } public Bitmap Bitmap { get { return bitmap; } set { if (value != null) { NullAndDispose(ref crbNormal); NullAndDispose(ref crbGrayed); } bitmap = value; if (bitmap != null) { crbNormal = new CachedResizedBitmap(value, false); crbGrayed = new CachedResizedBitmap(MakeGray(value), true); crop = new DualRects(PointF.Empty, bitmap.Size) { Real = new Rectangle( bitmap.Width / 4, bitmap.Height / 4, Math.Max(1, bitmap.Width / 2), Math.Max(1, bitmap.Height / 2)) }; OnCropRectangleChanged(); } PerformLayout(); Invalidate(); } } private Bitmap MakeGray(Bitmap orig) { Bitmap grayed = new Bitmap(orig); using (Graphics g = Graphics.FromImage(grayed)) { using (Brush b = new SolidBrush(Color.FromArgb(128, Color.Gray))) g.FillRectangle(b, 0, 0, grayed.Width, grayed.Height); } return grayed; } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left) { AnchorStyles anchor = cropStrategy.HitTest(crop.Virtual, e.Location); if (anchor != AnchorStyles.None) { cropStrategy.BeginDrag( crop.Virtual, e.Location, anchor, crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height)); Capture = true; } } } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (cropStrategy.IsDragging && e.Button == MouseButtons.Left) { cropStrategy.EndDrag(); Capture = false; OnCropRectangleChanged(); } } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (cropStrategy.IsDragging) { Rectangle originalRect = crop.Virtual; crop.Virtual = cropStrategy.GetNewBounds(PointToClient(MousePosition)); InvalidateForRectChange(originalRect, crop.Virtual); } else if (e.Button == MouseButtons.None) Cursor = ChooseCursor(crop.Virtual, e.Location); } private void InvalidateForRectChange(Rectangle oldRect, Rectangle newRect) { int borderWidth = BoundsWithHandles.HANDLE_SIZE * 2; InvalidateBorder(oldRect, borderWidth); InvalidateBorder(newRect, borderWidth); if (gridLines) { InvalidateGridlines(oldRect); InvalidateGridlines(newRect); } using (Region region = new Region(oldRect)) { region.Xor(newRect); Invalidate(region); } } private void InvalidateBorder(Rectangle rect, int width) { rect.Inflate(width / 2, width / 2); using (Region region = new Region(rect)) { rect.Inflate(-width, -width); region.Exclude(rect); Invalidate(region); } } private void InvalidateGridlines(Rectangle rect) { CalculateGridlines(rect, out int x1, out int x2, out int y1, out int y2); using (Region gridRegion = new Region()) { gridRegion.MakeEmpty(); gridRegion.Union(new Rectangle(x1, rect.Top, 1, rect.Height)); gridRegion.Union(new Rectangle(x2, rect.Top, 1, rect.Height)); gridRegion.Union(new Rectangle(rect.Left, y1, rect.Width, 1)); gridRegion.Union(new Rectangle(rect.Left, y2, rect.Width, 1)); Invalidate(gridRegion); } } private Cursor ChooseCursor(Rectangle sizeRect, Point point) { AnchorStyles anchor = cropStrategy.HitTest(sizeRect, point); switch (anchor) { case AnchorStyles.Left: case AnchorStyles.Right: return Cursors.SizeWE; case AnchorStyles.Top: case AnchorStyles.Bottom: return Cursors.SizeNS; case AnchorStyles.Top | AnchorStyles.Left: case AnchorStyles.Bottom | AnchorStyles.Right: return Cursors.SizeNWSE; case AnchorStyles.Top | AnchorStyles.Right: case AnchorStyles.Bottom | AnchorStyles.Left: return Cursors.SizeNESW; case AnchorStyles.None: return Cursors.Default; case ANCHOR_ALL: return Cursors.SizeAll; default: Debug.Fail("Unexpected anchor: " + anchor); return Cursors.Default; } } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); Invalidate(); } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); Invalidate(); } public bool ProcessCommandKey(ref Message msg, Keys keyData) { return ProcessCmdKey(ref msg, keyData); } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { switch (keyData) { case Keys.Up | Keys.Control: case Keys.Up: return AdjustCropRectangle(0, -1, 0, 0); case Keys.Down | Keys.Control: case Keys.Down: return AdjustCropRectangle(0, 1, 0, 0); case Keys.Left | Keys.Control: case Keys.Left: return AdjustCropRectangle(-1, 0, 0, 0); case Keys.Right | Keys.Control: case Keys.Right: return AdjustCropRectangle(1, 0, 0, 0); case Keys.Left | Keys.Shift: return AdjustCropRectangle(0, 0, -1, 0); case Keys.Right | Keys.Shift: return AdjustCropRectangle(0, 0, 1, 0); case Keys.Up | Keys.Shift: return AdjustCropRectangle(0, 0, 0, -1); case Keys.Down | Keys.Shift: return AdjustCropRectangle(0, 0, 0, 1); } return base.ProcessCmdKey(ref msg, keyData); } private bool AdjustCropRectangle(int xOffset, int yOffset, int xGrow, int yGrow) { Rectangle orig = crop.Virtual; Rectangle result = cropStrategy.AdjustRectangle( crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height), orig, xOffset, yOffset, xGrow, yGrow); if (orig != result) { crop.Virtual = result; fireCropChangedOnKeyUp = true; InvalidateForRectChange(orig, result); } return true; } protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); if (fireCropChangedOnKeyUp) { fireCropChangedOnKeyUp = false; OnCropRectangleChanged(); } } protected override void OnLayout(LayoutEventArgs e) { if (bitmap == null) return; float scaleFactor = Math.Min( (float)Width / bitmap.Width, (float)Height / bitmap.Height); Rectangle realRect = crop.Real; SizeF scale; PointF offset; if (scaleFactor > 1.0f) { scale = new SizeF(1, 1); offset = new PointF((Width - bitmap.Width) / 2, (Height - bitmap.Height) / 2); } else { offset = Point.Empty; scale = new SizeF(scaleFactor, scaleFactor); offset.X = (Width - (bitmap.Width * scale.Width)) / 2; offset.Y = (Height - (bitmap.Height * scale.Height)) / 2; } crop = new DualRects(offset, scale) { Real = realRect }; Size virtualBitmapSize = crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height).Size; crbNormal.Resize(virtualBitmapSize); crbGrayed.Resize(virtualBitmapSize); } protected override void OnPaint(PaintEventArgs e) { e.Graphics.InterpolationMode = InterpolationMode.Default; e.Graphics.SmoothingMode = SmoothingMode.HighSpeed; e.Graphics.CompositingMode = CompositingMode.SourceCopy; e.Graphics.CompositingQuality = CompositingQuality.HighSpeed; using (Brush b = new SolidBrush(BackColor)) e.Graphics.FillRectangle(b, ClientRectangle); if (bitmap == null) return; Rectangle bitmapRect = crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height); e.Graphics.DrawImage(crbGrayed.ResizedBitmap, bitmapRect); Rectangle normalSrcRect = crop.Virtual; normalSrcRect.Offset(-bitmapRect.X, -bitmapRect.Y); e.Graphics.DrawImage(crbNormal.ResizedBitmap, crop.Virtual, normalSrcRect, GraphicsUnit.Pixel); e.Graphics.CompositingMode = CompositingMode.SourceOver; Rectangle cropDrawRect = crop.Virtual; cropDrawRect.Width -= 1; cropDrawRect.Height -= 1; using (Brush b = new SolidBrush(Color.FromArgb(200, Color.White))) using (Pen p = new Pen(b, 1)) e.Graphics.DrawRectangle(p, cropDrawRect); if (gridLines) { CalculateGridlines(crop.Virtual, out int x1, out int x2, out int y1, out int y2); using (Brush b = new SolidBrush(Color.FromArgb(128, Color.Gray))) using (Pen p = new Pen(b, 1)) { e.Graphics.DrawLine(p, cropDrawRect.Left, y1, cropDrawRect.Right, y1); e.Graphics.DrawLine(p, cropDrawRect.Left, y2, cropDrawRect.Right, y2); e.Graphics.DrawLine(p, x1, cropDrawRect.Top, x1, cropDrawRect.Bottom); e.Graphics.DrawLine(p, x2, cropDrawRect.Top, x2, cropDrawRect.Bottom); } } if (Focused) { Rectangle focusRect = cropDrawRect; focusRect.Inflate(2, 2); ControlPaint.DrawFocusRectangle(e.Graphics, focusRect); } BoundsWithHandles boundsWithHandles = new BoundsWithHandles(cropStrategy.AspectRatio == null ? true : false) { Bounds = cropDrawRect }; using (Pen p = new Pen(SystemColors.ControlDarkDark, 1f)) foreach (Rectangle rect in boundsWithHandles.GetHandles()) { e.Graphics.FillRectangle(SystemBrushes.Window, rect); e.Graphics.DrawRectangle(p, rect); } } private static void CalculateGridlines(Rectangle cropDrawRect, out int x1, out int x2, out int y1, out int y2) { int yThird = cropDrawRect.Height / 3; y1 = cropDrawRect.Top + yThird; y2 = cropDrawRect.Top + yThird * 2; int xThird = cropDrawRect.Width / 3; x1 = cropDrawRect.Left + xThird; x2 = cropDrawRect.Left + xThird * 2; } private class CachedResizedBitmap : IDisposable { private readonly Bitmap original; private bool originalIsOwned; private Bitmap resized; private Size? currentSize; public CachedResizedBitmap(Bitmap original, bool takeOwnership) { this.original = original; this.originalIsOwned = takeOwnership; } public void Dispose() { Reset(); if (originalIsOwned) { originalIsOwned = false; // allows safe multiple disposal original.Dispose(); } } public void Reset() { Bitmap tmp = resized; resized = null; currentSize = null; if (tmp != null) tmp.Dispose(); } public void Resize(Size size) { size = new Size(Math.Max(size.Width, 1), Math.Max(size.Height, 1)); Reset(); Bitmap newBitmap = new Bitmap(original, size); using (Graphics g = Graphics.FromImage(newBitmap)) g.DrawImage(original, 0, 0, newBitmap.Width, newBitmap.Height); resized = newBitmap; currentSize = size; } public Size CurrentSize { get { return currentSize ?? original.Size; } } public Bitmap ResizedBitmap { get { return resized ?? original; } } } public abstract class CropStrategy { protected const int MIN_WIDTH = 5; protected const int MIN_HEIGHT = 5; private bool dragging = false; protected Rectangle initialBounds; protected Point initialLoc; protected AnchorStyles anchor; protected Rectangle? container; public virtual void BeginDrag(Rectangle initialBounds, Point initalLoc, AnchorStyles anchor, Rectangle? container) { dragging = true; this.initialBounds = initialBounds; this.initialLoc = initalLoc; this.anchor = anchor; this.container = container; } public virtual double? AspectRatio { get { return null; } } public virtual void EndDrag() { dragging = false; } public bool IsDragging { get { return dragging; } } public virtual Rectangle GetNewBounds(Point newLoc) { Rectangle newRect = initialBounds; if (anchor == ANCHOR_ALL) // move newRect = DoMove(newLoc); else // resize newRect = DoResize(newLoc); if (container != null) newRect.Intersect(container.Value); return newRect; } public abstract Rectangle AdjustRectangle(Rectangle cont, Rectangle rect, int xOffset, int yOffset, int xGrow, int yGrow); protected static int Round(double dblVal) { return (int)Math.Round(dblVal); } protected static int Round(float fltVal) { return (int)Math.Round(fltVal); } protected virtual Rectangle DoMove(Point newLoc) { Rectangle newRect = initialBounds; int deltaX = newLoc.X - initialLoc.X; int deltaY = newLoc.Y - initialLoc.Y; newRect.Offset(deltaX, deltaY); if (container != null) { Rectangle cont = container.Value; if (cont.Left > newRect.Left) newRect.Offset(cont.Left - newRect.Left, 0); else if (cont.Right < newRect.Right) newRect.Offset(cont.Right - newRect.Right, 0); if (cont.Top > newRect.Top) newRect.Offset(0, cont.Top - newRect.Top); else if (cont.Bottom < newRect.Bottom) newRect.Offset(0, cont.Bottom - newRect.Bottom); } return newRect; } protected abstract Rectangle DoResize(Point newLoc); [Flags] private enum HT { None = 0, Left = 1, Top = 2, Right = 4, Bottom = 8, AlmostLeft = 16, AlmostTop = 32, AlmostRight = 64, AlmostBottom = 128, Mask_Horizontal = Left | AlmostLeft | Right | AlmostRight, Mask_Vertical = Top | AlmostTop | Bottom | AlmostBottom, } public virtual AnchorStyles HitTest(Rectangle sizeRect, Point point) { sizeRect.Inflate(1, 1); if (!sizeRect.Contains(point)) return AnchorStyles.None; HT hitTest = HT.None; Test(sizeRect.Right - point.X, HT.Right, HT.AlmostRight, ref hitTest); Test(sizeRect.Bottom - point.Y, HT.Bottom, HT.AlmostBottom, ref hitTest); Test(point.X - sizeRect.Left, HT.Left, HT.AlmostLeft, ref hitTest); Test(point.Y - sizeRect.Top, HT.Top, HT.AlmostTop, ref hitTest); RemoveConflicts(ref hitTest); switch (hitTest) { case HT.Left: return AnchorStyles.Left; case HT.Top: return AnchorStyles.Top; case HT.Right: return AnchorStyles.Right; case HT.Bottom: return AnchorStyles.Bottom; case HT.Left | HT.Top: case HT.Left | HT.AlmostTop: case HT.Top | HT.AlmostLeft: return AnchorStyles.Top | AnchorStyles.Left; case HT.Right | HT.Top: case HT.Right | HT.AlmostTop: case HT.Top | HT.AlmostRight: return AnchorStyles.Top | AnchorStyles.Right; case HT.Right | HT.Bottom: case HT.Right | HT.AlmostBottom: case HT.Bottom | HT.AlmostRight: return AnchorStyles.Bottom | AnchorStyles.Right; case HT.Left | HT.Bottom: case HT.Left | HT.AlmostBottom: case HT.Bottom | HT.AlmostLeft: return AnchorStyles.Bottom | AnchorStyles.Left; default: return ANCHOR_ALL; } } private static void RemoveConflicts(ref HT hitTest) { TestClearAndSet(ref hitTest, HT.Right, HT.Mask_Horizontal); TestClearAndSet(ref hitTest, HT.Left, HT.Mask_Horizontal); TestClearAndSet(ref hitTest, HT.AlmostRight, HT.Mask_Horizontal); TestClearAndSet(ref hitTest, HT.AlmostLeft, HT.Mask_Horizontal); TestClearAndSet(ref hitTest, HT.Bottom, HT.Mask_Vertical); TestClearAndSet(ref hitTest, HT.Top, HT.Mask_Vertical); TestClearAndSet(ref hitTest, HT.AlmostBottom, HT.Mask_Vertical); TestClearAndSet(ref hitTest, HT.AlmostTop, HT.Mask_Vertical); } private static void TestClearAndSet(ref HT val, HT test, HT clearMask) { if (test == (test & val)) { val &= ~clearMask; val |= test; } } private static void Test(int distance, HT exactResult, HT fuzzyResult, ref HT hitTest) { hitTest |= distance < 0 ? 0 : distance < 5 ? exactResult : distance < 10 ? fuzzyResult : 0; } } public class FixedAspectRatioCropStrategy : FreeCropStrategy { private double aspectRatio; public FixedAspectRatioCropStrategy(double aspectRatio) { this.aspectRatio = aspectRatio; } public override double? AspectRatio { get { return aspectRatio; } } public override Rectangle AdjustRectangle(Rectangle cont, Rectangle rect, int xOffset, int yOffset, int xGrow, int yGrow) { Rectangle result = base.AdjustRectangle(cont, rect, xOffset, yOffset, xGrow, yGrow); if (xGrow != 0) result.Height = Math.Max(MIN_HEIGHT, Round(result.Width / aspectRatio)); else if (yGrow != 0) result.Width = Math.Max(MIN_WIDTH, Round(result.Height * aspectRatio)); // too far--revert! if (result.Bottom > cont.Bottom || result.Right > cont.Right) result = rect; return result; } public Rectangle ConformCropRectangle(Rectangle containerRect, Rectangle cropRect) { // try to preserve the same number of pixels int numOfPixels = cropRect.Width * cropRect.Height; PointF center = new PointF(cropRect.Left + cropRect.Width / 2f, cropRect.Top + cropRect.Height / 2f); double height = Math.Sqrt(numOfPixels / aspectRatio); double width = aspectRatio * height; PointF newLoc = new PointF(center.X - (float)width / 2f, center.Y - (float)height / 2f); return new Rectangle( Convert.ToInt32(newLoc.X), Convert.ToInt32(newLoc.Y), Convert.ToInt32(width), Convert.ToInt32(height)); } public override AnchorStyles HitTest(Rectangle sizeRect, Point point) { AnchorStyles hitTest = base.HitTest(sizeRect, point); if (AnchorStyles.None == (hitTest & (AnchorStyles.Left | AnchorStyles.Right))) return AnchorStyles.None; if (AnchorStyles.None == (hitTest & (AnchorStyles.Top | AnchorStyles.Bottom))) return AnchorStyles.None; return hitTest; } protected override Rectangle DoResize(Point newLoc) { bool up = AnchorStyles.Top == (anchor & AnchorStyles.Top); bool left = AnchorStyles.Left == (anchor & AnchorStyles.Left); PointF origin = new PointF( initialBounds.Left + (left ? initialBounds.Width : 0), initialBounds.Top + (up ? initialBounds.Height : 0)); double desiredAngle = Math.Atan2( 1d * (up ? -1 : 1), 1d * aspectRatio * (left ? -1 : 1)); double actualAngle = Math.Atan2( newLoc.Y - origin.Y, newLoc.X - origin.X); double angleDiff = Math.Abs(actualAngle - desiredAngle); if (angleDiff >= Math.PI / 2) // >=90 degrees--too much angle! return base.DoResize(new Point((int)origin.X, (int)origin.Y)); double distance = Distance(origin, newLoc); double resizeMagnitude = Math.Cos(angleDiff) * distance; double xMagnitude = resizeMagnitude * Math.Cos(desiredAngle); double yMagnitude = resizeMagnitude * Math.Sin(desiredAngle); newLoc.X = Round(origin.X + xMagnitude); newLoc.Y = Round(origin.Y + yMagnitude); Rectangle newRect = base.DoResize(newLoc); if (container != null) { Rectangle newRectConstrained = newRect; newRectConstrained.Intersect(container.Value); if (!newRectConstrained.Equals(newRect)) { int newWidth = Round(Math.Min(newRectConstrained.Width, newRectConstrained.Height * aspectRatio)); int newHeight = Round(Math.Min(newRectConstrained.Height, newRectConstrained.Width / aspectRatio)); newRect.Width = newWidth; newRect.Height = newHeight; if (left) newRect.Location = new Point(initialBounds.Right - newRect.Width, newRect.Top); if (up) newRect.Location = new Point(newRect.Left, initialBounds.Bottom - newRect.Height); } } return newRect; } private double Distance(PointF pFrom, PointF pTo) { double deltaX = Math.Abs((double)(pTo.X - pFrom.X)); double deltaY = Math.Abs((double)(pTo.Y - pFrom.Y)); return Math.Sqrt( deltaX * deltaX + deltaY * deltaY ); } private PointF Rotate(PointF origin, double angleRadians, PointF point) { float x, y; x = point.X - origin.X; y = point.Y - origin.Y; point.X = (float)(x * Math.Cos(angleRadians) - y * Math.Sin(angleRadians)); point.Y = (float)(y * Math.Cos(angleRadians) - x * Math.Sin(angleRadians)); point.X += origin.X; point.Y += origin.Y; return point; } } public class FreeCropStrategy : CropStrategy { protected override Rectangle DoResize(Point newLoc) { Rectangle newRect = initialBounds; int deltaX = newLoc.X - initialLoc.X; int deltaY = newLoc.Y - initialLoc.Y; switch (anchor & (AnchorStyles.Left | AnchorStyles.Right)) { case AnchorStyles.Left: if (MIN_WIDTH >= initialBounds.Width - deltaX) deltaX = initialBounds.Width - MIN_WIDTH; newRect.Width -= deltaX; newRect.Offset(deltaX, 0); break; case AnchorStyles.Right: if (MIN_WIDTH >= initialBounds.Width + deltaX) deltaX = -initialBounds.Width + MIN_WIDTH; newRect.Width += deltaX; break; } switch (anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) { case AnchorStyles.Top: if (MIN_HEIGHT >= initialBounds.Height - deltaY) deltaY = initialBounds.Height - MIN_HEIGHT; newRect.Height -= deltaY; newRect.Offset(0, deltaY); break; case AnchorStyles.Bottom: if (MIN_HEIGHT >= initialBounds.Height + deltaY) deltaY = -initialBounds.Height + MIN_HEIGHT; newRect.Height += deltaY; break; } return newRect; } public override Rectangle AdjustRectangle(Rectangle cont, Rectangle rect, int xOffset, int yOffset, int xGrow, int yGrow) { Debug.Assert((new[] { xOffset, yOffset, xGrow, yGrow }).Max() <= 1, "AdjustRectangle doesn't work well with values larger than 1--edge cases in FixedAspectRatioCropStrategy"); Debug.Assert((new[] { xOffset, yOffset, xGrow, yGrow }).Min() >= -1, "AdjustRectangle doesn't work well with values larger than 1--edge cases in FixedAspectRatioCropStrategy"); Debug.Assert((xOffset == 0 && yOffset == 0) || (xGrow == 0 && yGrow == 0), "Beware of changing offset and size with the same call--weird things may happen as you approach the edges of the container"); rect.X = Math.Max(cont.X, Math.Min(cont.Right - rect.Width, rect.X + xOffset)); rect.Y = Math.Max(cont.Y, Math.Min(cont.Bottom - rect.Height, rect.Y + yOffset)); rect.Width = Math.Max(MIN_WIDTH, Math.Min(cont.Right - rect.Left, rect.Width + xGrow)); rect.Height = Math.Max(MIN_HEIGHT, Math.Min(cont.Bottom - rect.Top, rect.Height + yGrow)); return rect; } } private class DualRects { private Rectangle r; private Rectangle v; private readonly PointF offset; private readonly SizeF scale; public DualRects(PointF offset, SizeF scale) { this.offset = offset; this.scale = scale; } public Rectangle Real { get { return r; } set { r = value; v = VirtualizeRect(r.X, r.Y, r.Width, r.Height); } } public Rectangle Virtual { get { return v; } set { v = value; r = RealizeRect(v.X, v.Y, v.Width, v.Height); } } public Rectangle RealizeRect(int x, int y, int width, int height) { return new Rectangle( (int)Math.Round((x - offset.X) / scale.Width), (int)Math.Round((y - offset.Y) / scale.Height), (int)Math.Round(width / scale.Width), (int)Math.Round(height / scale.Height) ); } public Rectangle VirtualizeRect(int x, int y, int width, int height) { return new Rectangle( (int)Math.Round(x * scale.Width + offset.X), (int)Math.Round(y * scale.Height + offset.Y), (int)Math.Round(width * scale.Width), (int)Math.Round(height * scale.Height) ); } } private class BoundsWithHandles { public const int HANDLE_SIZE = 5; private readonly bool includeSideHandles; private Rectangle bounds; public BoundsWithHandles(bool includeSideHandles) { this.includeSideHandles = includeSideHandles; } public Rectangle Bounds { get { return bounds; } set { bounds = value; } } public Rectangle[] GetHandles() { List<Rectangle> handles = new List<Rectangle>(includeSideHandles ? 8 : 4) { // top left MakeRect(bounds.Left, bounds.Top) }; if (includeSideHandles) handles.Add(MakeRect((bounds.Left + bounds.Right) / 2, bounds.Top)); handles.Add(MakeRect(bounds.Right, bounds.Top)); if (includeSideHandles) { handles.Add(MakeRect(bounds.Left, (bounds.Top + bounds.Bottom) / 2)); handles.Add(MakeRect(bounds.Right, (bounds.Top + bounds.Bottom) / 2)); } handles.Add(MakeRect(bounds.Left, bounds.Bottom)); if (includeSideHandles) handles.Add(MakeRect((bounds.Left + bounds.Right) / 2, bounds.Bottom)); handles.Add(MakeRect(bounds.Right, bounds.Bottom)); return handles.ToArray(); } private static Rectangle MakeRect(int x, int y) { return new Rectangle(x - (HANDLE_SIZE / 2), y - (HANDLE_SIZE / 2), HANDLE_SIZE, HANDLE_SIZE); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using Internal.Runtime.CompilerServices; namespace System { /// <summary> /// Represents a contiguous region of memory, similar to <see cref="ReadOnlySpan{T}"/>. /// Unlike <see cref="ReadOnlySpan{T}"/>, it is not a byref-like type. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] [DebuggerTypeProxy(typeof(MemoryDebugView<>))] public readonly struct ReadOnlyMemory<T> { // NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout, // as code uses Unsafe.As to cast between them. // The highest order bit of _index is used to discern whether _object is an array/string or an owned memory // if (_index >> 31) == 1, _object is an OwnedMemory<T> // else, _object is a T[] or string private readonly object _object; private readonly int _index; private readonly int _length; internal const int RemoveOwnedFlagBitMask = 0x7FFFFFFF; /// <summary> /// Creates a new memory over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); _object = array; _index = 0; _length = array.Length; } /// <summary> /// Creates a new memory over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array, int start, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); _object = array; _index = start; _length = length; } /// <summary>Creates a new memory over the existing object, start, and length. No validation is performed.</summary> /// <param name="obj">The target object.</param> /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlyMemory(object obj, int start, int length) { // No validation performed; caller must provide any necessary validation. _object = obj; _index = start; _length = length; } //Debugger Display = {T[length]} private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length); /// <summary> /// Defines an implicit conversion of an array to a <see cref="ReadOnlyMemory{T}"/> /// </summary> public static implicit operator ReadOnlyMemory<T>(T[] array) => new ReadOnlyMemory<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlyMemory{T}"/> /// </summary> public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> arraySegment) => new ReadOnlyMemory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count); /// <summary> /// Returns an empty <see cref="ReadOnlyMemory{T}"/> /// </summary> public static ReadOnlyMemory<T> Empty => default; /// <summary> /// The number of items in the memory. /// </summary> public int Length => _length; /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty => _length == 0; /// <summary> /// Forms a slice out of the given memory, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start) { if ((uint)start > (uint)_length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, _length - start); } /// <summary> /// Forms a slice out of the given memory, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, length); } /// <summary> /// Returns a span from the memory. /// </summary> public ReadOnlySpan<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) { return ((OwnedMemory<T>)_object).Span.Slice(_index & RemoveOwnedFlagBitMask, _length); } else if (typeof(T) == typeof(char) && _object is string s) { return new ReadOnlySpan<T>(ref Unsafe.As<char, T>(ref s.GetRawStringData()), s.Length).Slice(_index, _length); } else if (_object != null) { return new ReadOnlySpan<T>((T[])_object, _index, _length); } else { return default; } } } /// <summary> /// Copies the contents of the read-only memory into the destination. If the source /// and destination overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. /// /// <param name="destination">The Memory to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination is shorter than the source. /// </exception> /// </summary> public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span); /// <summary> /// Copies the contents of the readonly-only memory into the destination. If the source /// and destination overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. /// /// <returns>If the destination is shorter than the source, this method /// return false and no data is written to the destination.</returns> /// </summary> /// <param name="destination">The span to copy items into.</param> public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span); /// <summary>Creates a handle for the memory.</summary> /// <param name="pin"> /// If pin is true, the GC will not move the array until the returned <see cref="MemoryHandle"/> /// is disposed, enabling the memory's address can be taken and used. /// </param> public unsafe MemoryHandle Retain(bool pin = false) { MemoryHandle memoryHandle = default; if (pin) { if (_index < 0) { memoryHandle = ((OwnedMemory<T>)_object).Pin(); memoryHandle.AddOffset((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>()); } else if (typeof(T) == typeof(char) && _object is string s) { GCHandle handle = GCHandle.Alloc(s, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref s.GetRawStringData()), _index); memoryHandle = new MemoryHandle(null, pointer, handle); } else if (_object is T[] array) { var handle = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index); memoryHandle = new MemoryHandle(null, pointer, handle); } } else { if (_index < 0) { ((OwnedMemory<T>)_object).Retain(); memoryHandle = new MemoryHandle((OwnedMemory<T>)_object); } } return memoryHandle; } /// <summary> /// Copies the contents from the memory into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] ToArray() => Span.ToArray(); /// <summary>Determines whether the specified object is equal to the current object.</summary> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T> readOnlyMemory) { return Equals(readOnlyMemory); } else if (obj is Memory<T> memory) { return Equals(memory); } else { return false; } } /// <summary> /// Returns true if the memory points to the same array and has the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public bool Equals(ReadOnlyMemory<T> other) { return _object == other._object && _index == other._index && _length == other._length; } /// <summary>Returns the hash code for this <see cref="ReadOnlyMemory{T}"/></summary> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return _object != null ? CombineHashCodes(_object.GetHashCode(), _index.GetHashCode(), _length.GetHashCode()) : 0; } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } /// <summary>Gets the state of the memory as individual fields.</summary> /// <param name="start">The offset.</param> /// <param name="length">The count.</param> /// <returns>The object.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal object GetObjectStartLength(out int start, out int length) { start = _index; length = _length; return _object; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SmallTalk.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// *********************************************************************** // Copyright (c) 2009 Charlie Poole // // 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. // *********************************************************************** // **************************************************************** // Generated by the NUnit Syntax Generator // // Command Line: GenSyntax.exe SyntaxElements.txt // // DO NOT MODIFY THIS FILE DIRECTLY // **************************************************************** using System; using System.Collections; using System.ComponentModel; using NUnit.Framework.Constraints; namespace NUnit.Framework { /// <summary> /// Delegate used by tests that execute code and /// capture any thrown exception. /// </summary> public delegate void TestDelegate(); /// <summary> /// The Assert class contains a collection of static methods that /// implement the most common assertions used in NUnit. /// </summary> public class Assert { #region Constructor /// <summary> /// We don't actually want any instances of this object, but some people /// like to inherit from it to add other static methods. Hence, the /// protected constructor disallows any instances of this object. /// </summary> protected Assert() { } #endregion #region Assert Counting private static int counter = 0; /// <summary> /// Gets the number of assertions executed so far and /// resets the counter to zero. /// </summary> public static int Counter { get { int cnt = counter; counter = 0; return cnt; } } private static void IncrementAssertCount() { ++counter; } #endregion #region Equals and ReferenceEquals #if !NETCF /// <summary> /// The Equals method throws an AssertionException. This is done /// to make sure there is no mistake by calling this function. /// </summary> /// <param name="a"></param> /// <param name="b"></param> [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { throw new InvalidOperationException("Assert.Equals should not be used for Assertions"); } /// <summary> /// override the default ReferenceEquals to throw an AssertionException. This /// implementation makes sure there is no mistake in calling this function /// as part of Assert. /// </summary> /// <param name="a"></param> /// <param name="b"></param> public static new void ReferenceEquals(object a, object b) { throw new InvalidOperationException("Assert.ReferenceEquals should not be used for Assertions"); } #endif #endregion #region Utility Asserts #region Pass /// <summary> /// Throws a <see cref="SuccessException"/> with the message and arguments /// that are passed in. This allows a test to be cut short, with a result /// of success returned to NUnit. /// </summary> /// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void Pass(string message, params object[] args) { if (message == null) message = string.Empty; else if (args != null && args.Length > 0) message = string.Format(message, args); throw new SuccessException(message); } /// <summary> /// Throws a <see cref="SuccessException"/> with the message and arguments /// that are passed in. This allows a test to be cut short, with a result /// of success returned to NUnit. /// </summary> /// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param> static public void Pass(string message) { Assert.Pass(message, null); } /// <summary> /// Throws a <see cref="SuccessException"/> with the message and arguments /// that are passed in. This allows a test to be cut short, with a result /// of success returned to NUnit. /// </summary> static public void Pass() { Assert.Pass(string.Empty, null); } #endregion #region Fail /// <summary> /// Throw an assertion exception with a message and optional arguments /// </summary> /// <param name="message">The message, possibly with format placeholders</param> /// <param name="args">Arguments used in formatting the string</param> public static void Fail(string message, params object[] args) { throw new AssertionException(FormatMessage(message, args)); } /// <summary> /// Formats a message with any user-supplied arguments. /// </summary> /// <param name="message">The message.</param> /// <param name="args">The args.</param> private static string FormatMessage(string message, params object[] args) { if (message == null) return string.Empty; else if (args != null && args.Length > 0) return string.Format(message, args); else return message; } #endregion #region Ignore /// <summary> /// Throws an <see cref="IgnoreException"/> with the message and arguments /// that are passed in. This causes the test to be reported as ignored. /// </summary> /// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void Ignore(string message, params object[] args) { if (message == null) message = string.Empty; else if (args != null && args.Length > 0) message = string.Format(message, args); throw new IgnoreException(message); } /// <summary> /// Throws an <see cref="IgnoreException"/> with the message that is /// passed in. This causes the test to be reported as ignored. /// </summary> /// <param name="message">The message to initialize the <see cref="AssertionException"/> with.</param> static public void Ignore(string message) { Assert.Ignore(message, null); } /// <summary> /// Throws an <see cref="IgnoreException"/>. /// This causes the test to be reported as ignored. /// </summary> static public void Ignore() { Assert.Ignore(string.Empty, null); } #endregion #region InConclusive /// <summary> /// Throws an <see cref="InconclusiveException"/> with the message and arguments /// that are passed in. This causes the test to be reported as inconclusive. /// </summary> /// <param name="message">The message to initialize the <see cref="InconclusiveException"/> with.</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void Inconclusive(string message, params object[] args) { if (message == null) message = string.Empty; else if (args != null && args.Length > 0) message = string.Format(message, args); throw new InconclusiveException(message); } /// <summary> /// Throws an <see cref="InconclusiveException"/> with the message that is /// passed in. This causes the test to be reported as inconclusive. /// </summary> /// <param name="message">The message to initialize the <see cref="InconclusiveException"/> with.</param> static public void Inconclusive(string message) { Assert.Inconclusive(message, null); } /// <summary> /// Throws an <see cref="InconclusiveException"/>. /// This causes the test to be reported as Inconclusive. /// </summary> static public void Inconclusive() { Assert.Inconclusive(string.Empty, null); } #endregion #endregion #region Assert.That #region Object /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. /// </summary> /// <param name="expression">A Constraint to be applied</param> /// <param name="actual">The actual value to test</param> static public void That(object actual, IResolveConstraint expression) { Assert.That(actual, expression, null, null); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. /// </summary> /// <param name="expression">A Constraint to be applied</param> /// <param name="actual">The actual value to test</param> /// <param name="message">The message that will be displayed on failure</param> static public void That(object actual, IResolveConstraint expression, string message) { Assert.That(actual, expression, message, null); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. /// </summary> /// <param name="expression">A Constraint to be applied</param> /// <param name="actual">The actual value to test</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void That(object actual, IResolveConstraint expression, string message, params object[] args) { Constraint constraint = expression.Resolve(); Assert.IncrementAssertCount(); if (!constraint.Matches(actual)) { MessageWriter writer = new TextMessageWriter(message, args); constraint.WriteMessageTo(writer); throw new AssertionException(writer.ToString()); } } #endregion #region Boolean /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display if the condition is false</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void That(bool condition, string message, params object[] args) { Assert.That(condition, Is.True, message, args); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display if the condition is false</param> static public void That(bool condition, string message) { Assert.That(condition, Is.True, message, null); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> static public void That(bool condition) { Assert.That(condition, Is.True, null, null); } #endregion #endregion #region True /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display if the condition is false</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void True(bool condition, string message, params object[] args) { Assert.That(condition, Is.True, message, args); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display if the condition is false</param> static public void True(bool condition, string message) { Assert.True(condition, message, null); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> static public void True(bool condition) { Assert.True(condition, null, null); } #endregion #region False /// <summary> /// Asserts that a condition is false. If the condition is true the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display if the condition is true</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void False(bool condition, string message, params object[] args) { Assert.That(condition, Is.False, message, args); } /// <summary> /// Asserts that a condition is false. If the condition is true the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display if the condition is true</param> static public void False(bool condition, string message) { Assert.False(condition, message, null); } /// <summary> /// Asserts that a condition is false. If the condition is true the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> static public void False(bool condition) { Assert.False(condition, string.Empty, null); } #endregion #region NotNull /// <summary> /// Verifies that the object that is passed in is not equal to <code>null</code> /// If the object is <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> /// <param name="message">The message to be displayed when the object is null</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void NotNull(Object anObject, string message, params object[] args) { Assert.That(anObject, Is.Not.Null, message, args); } /// <summary> /// Verifies that the object that is passed in is not equal to <code>null</code> /// If the object is <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> /// <param name="message">The message to be displayed when the object is null</param> static public void NotNull(Object anObject, string message) { Assert.NotNull(anObject, message, null); } /// <summary> /// Verifies that the object that is passed in is not equal to <code>null</code> /// If the object is <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> static public void NotNull(Object anObject) { Assert.NotNull(anObject, string.Empty, null); } #endregion #region Null /// <summary> /// Verifies that the object that is passed in is equal to <code>null</code> /// If the object is not <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> /// <param name="message">The message to be displayed when the object is not null</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void Null(Object anObject, string message, params object[] args) { Assert.That(anObject, Is.Null, message, args); } /// <summary> /// Verifies that the object that is passed in is equal to <code>null</code> /// If the object is not <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> /// <param name="message">The message to be displayed when the object is not null</param> static public void Null(Object anObject, string message) { Assert.Null(anObject, message, null); } /// <summary> /// Verifies that the object that is passed in is equal to <code>null</code> /// If the object is not null <code>null</code> then an <see cref="AssertionException"/> /// is thrown. /// </summary> /// <param name="anObject">The object that is to be tested</param> static public void Null(Object anObject) { Assert.Null(anObject, string.Empty, null); } #endregion } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim 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.IO; using System.Text; using System.Xml; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Framework.Serialization.External { /// <summary> /// Serialize and deserialize region settings as an external format. /// </summary> public class RegionSettingsSerializer { protected static ASCIIEncoding m_asciiEncoding = new ASCIIEncoding(); /// <summary> /// Deserialize settings /// </summary> /// <param name="serializedSettings"></param> /// <returns></returns> /// <exception cref="System.Xml.XmlException"></exception> public static RegionSettings Deserialize(byte[] serializedSettings) { return Deserialize(m_asciiEncoding.GetString(serializedSettings, 0, serializedSettings.Length)); } /// <summary> /// Deserialize settings /// </summary> /// <param name="serializedSettings"></param> /// <returns></returns> /// <exception cref="System.Xml.XmlException"></exception> public static RegionSettings Deserialize(string serializedSettings) { RegionSettings settings = new RegionSettings(); StringReader sr = new StringReader(serializedSettings); XmlTextReader xtr = new XmlTextReader(sr); xtr.ReadStartElement("RegionSettings"); xtr.ReadStartElement("General"); while (xtr.Read() && xtr.NodeType != XmlNodeType.EndElement) { switch (xtr.Name) { case "AllowDamage": settings.AllowDamage = bool.Parse(xtr.ReadElementContentAsString()); break; case "AllowLandResell": settings.AllowLandResell = bool.Parse(xtr.ReadElementContentAsString()); break; case "AllowLandJoinDivide": settings.AllowLandJoinDivide = bool.Parse(xtr.ReadElementContentAsString()); break; case "BlockFly": settings.BlockFly = bool.Parse(xtr.ReadElementContentAsString()); break; case "BlockLandShowInSearch": settings.BlockShowInSearch = bool.Parse(xtr.ReadElementContentAsString()); break; case "BlockTerraform": settings.BlockTerraform = bool.Parse(xtr.ReadElementContentAsString()); break; case "DisableCollisions": settings.DisableCollisions = bool.Parse(xtr.ReadElementContentAsString()); break; case "DisablePhysics": settings.DisablePhysics = bool.Parse(xtr.ReadElementContentAsString()); break; case "DisableScripts": settings.DisableScripts = bool.Parse(xtr.ReadElementContentAsString()); break; case "MaturityRating": settings.Maturity = int.Parse(xtr.ReadElementContentAsString()); break; case "RestrictPushing": settings.RestrictPushing = bool.Parse(xtr.ReadElementContentAsString()); break; case "AgentLimit": settings.AgentLimit = int.Parse(xtr.ReadElementContentAsString()); break; case "ObjectBonus": settings.ObjectBonus = double.Parse(xtr.ReadElementContentAsString()); break; } } xtr.ReadEndElement(); xtr.ReadStartElement("GroundTextures"); while (xtr.Read() && xtr.NodeType != XmlNodeType.EndElement) { switch (xtr.Name) { case "Texture1": settings.TerrainTexture1 = UUID.Parse(xtr.ReadElementContentAsString()); break; case "Texture2": settings.TerrainTexture2 = UUID.Parse(xtr.ReadElementContentAsString()); break; case "Texture3": settings.TerrainTexture3 = UUID.Parse(xtr.ReadElementContentAsString()); break; case "Texture4": settings.TerrainTexture4 = UUID.Parse(xtr.ReadElementContentAsString()); break; case "ElevationLowSW": settings.Elevation1SW = double.Parse(xtr.ReadElementContentAsString()); break; case "ElevationLowNW": settings.Elevation1NW = double.Parse(xtr.ReadElementContentAsString()); break; case "ElevationLowSE": settings.Elevation1SE = double.Parse(xtr.ReadElementContentAsString()); break; case "ElevationLowNE": settings.Elevation1NE = double.Parse(xtr.ReadElementContentAsString()); break; case "ElevationHighSW": settings.Elevation2SW = double.Parse(xtr.ReadElementContentAsString()); break; case "ElevationHighNW": settings.Elevation2NW = double.Parse(xtr.ReadElementContentAsString()); break; case "ElevationHighSE": settings.Elevation2SE = double.Parse(xtr.ReadElementContentAsString()); break; case "ElevationHighNE": settings.Elevation2NE = double.Parse(xtr.ReadElementContentAsString()); break; } } xtr.ReadEndElement(); xtr.ReadStartElement("Terrain"); while (xtr.Read() && xtr.NodeType != XmlNodeType.EndElement) { switch (xtr.Name) { case "WaterHeight": settings.WaterHeight = double.Parse(xtr.ReadElementContentAsString()); break; case "TerrainRaiseLimit": settings.TerrainRaiseLimit = double.Parse(xtr.ReadElementContentAsString()); break; case "TerrainLowerLimit": settings.TerrainLowerLimit = double.Parse(xtr.ReadElementContentAsString()); break; case "UseEstateSun": settings.UseEstateSun = bool.Parse(xtr.ReadElementContentAsString()); break; case "FixedSun": settings.FixedSun = bool.Parse(xtr.ReadElementContentAsString()); break; } } xtr.Close(); sr.Close(); return settings; } public static string Serialize(RegionSettings settings) { StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); xtw.Formatting = Formatting.Indented; xtw.WriteStartDocument(); xtw.WriteStartElement("RegionSettings"); xtw.WriteStartElement("General"); xtw.WriteElementString("AllowDamage", settings.AllowDamage.ToString()); xtw.WriteElementString("AllowLandResell", settings.AllowLandResell.ToString()); xtw.WriteElementString("AllowLandJoinDivide", settings.AllowLandJoinDivide.ToString()); xtw.WriteElementString("BlockFly", settings.BlockFly.ToString()); xtw.WriteElementString("BlockLandShowInSearch", settings.BlockShowInSearch.ToString()); xtw.WriteElementString("BlockTerraform", settings.BlockTerraform.ToString()); xtw.WriteElementString("DisableCollisions", settings.DisableCollisions.ToString()); xtw.WriteElementString("DisablePhysics", settings.DisablePhysics.ToString()); xtw.WriteElementString("DisableScripts", settings.DisableScripts.ToString()); xtw.WriteElementString("MaturityRating", settings.Maturity.ToString()); xtw.WriteElementString("RestrictPushing", settings.RestrictPushing.ToString()); xtw.WriteElementString("AgentLimit", settings.AgentLimit.ToString()); xtw.WriteElementString("ObjectBonus", settings.ObjectBonus.ToString()); xtw.WriteEndElement(); xtw.WriteStartElement("GroundTextures"); xtw.WriteElementString("Texture1", settings.TerrainTexture1.ToString()); xtw.WriteElementString("Texture2", settings.TerrainTexture2.ToString()); xtw.WriteElementString("Texture3", settings.TerrainTexture3.ToString()); xtw.WriteElementString("Texture4", settings.TerrainTexture4.ToString()); xtw.WriteElementString("ElevationLowSW", settings.Elevation1SW.ToString()); xtw.WriteElementString("ElevationLowNW", settings.Elevation1NW.ToString()); xtw.WriteElementString("ElevationLowSE", settings.Elevation1SE.ToString()); xtw.WriteElementString("ElevationLowNE", settings.Elevation1NE.ToString()); xtw.WriteElementString("ElevationHighSW", settings.Elevation2SW.ToString()); xtw.WriteElementString("ElevationHighNW", settings.Elevation2NW.ToString()); xtw.WriteElementString("ElevationHighSE", settings.Elevation2SE.ToString()); xtw.WriteElementString("ElevationHighNE", settings.Elevation2NE.ToString()); xtw.WriteEndElement(); xtw.WriteStartElement("Terrain"); xtw.WriteElementString("WaterHeight", settings.WaterHeight.ToString()); xtw.WriteElementString("TerrainRaiseLimit", settings.TerrainRaiseLimit.ToString()); xtw.WriteElementString("TerrainLowerLimit", settings.TerrainLowerLimit.ToString()); xtw.WriteElementString("UseEstateSun", settings.UseEstateSun.ToString()); xtw.WriteElementString("FixedSun", settings.FixedSun.ToString()); // XXX: Need to expose interface to get sun phase information from sun module // xtw.WriteStartElement("SunPhase", xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.Close(); sw.Close(); return sw.ToString(); } } }
using System; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Mono.Terminal { public delegate string[] TabExpansionEvent(string hardPrefix, string replacable); public class TabExpanderUI { private const int NO_ITEM_SELECTED = -1; private const int ASKING_USER = -2; private const int NOT_INITIALIZED = -3; private string _hardPrefix; private string _softPrefix; private string[] _expandandedItems; private int _selectedItem = NOT_INITIALIZED; private bool _userWasAsked; private int _maxWrittenX; private int _maxWrittenY; private int _lastRenderNumRows; private bool _abortedOrAccepted; public int RenderStartX { get; private set; } public int RenderStartY { get; private set; } public bool Running { get; private set; } public TabExpansionEvent TabExpansionEvent; public bool HasSelection { get { return _selectedItem >= 0; } } public TabExpanderUI() { Running = false; _abortedOrAccepted = true; } public bool HandleKey(ConsoleKeyInfo keyInfo) { if (keyInfo.Modifiers != 0) { return false; } switch (keyInfo.Key) { case ConsoleKey.Enter: if (_selectedItem == ASKING_USER) { goto case ConsoleKey.Tab; } else { Accept(); return _selectedItem >= 0; } case ConsoleKey.Tab: ChooseNext(); return true; case ConsoleKey.Escape: Abort(true); return true; case ConsoleKey.DownArrow: case ConsoleKey.UpArrow: case ConsoleKey.LeftArrow: case ConsoleKey.RightArrow: if (_selectedItem == ASKING_USER) { Abort(true); } return ChangeSelection(keyInfo.Key); default: if (_selectedItem == ASKING_USER) { Abort(true); } return false; } } private bool ChangeSelection(ConsoleKey key) { if (_selectedItem < 0 || _lastRenderNumRows < 1) { return false; // only handle selection if something is already selected } // otherwise select depending on last rendering if (key == ConsoleKey.UpArrow && _selectedItem > 0) { _selectedItem--; } else if (key == ConsoleKey.DownArrow && _selectedItem < _expandandedItems.Length - 1) { _selectedItem++; } else if (key == ConsoleKey.LeftArrow) { _selectedItem -= _lastRenderNumRows; // check for underflow if (_selectedItem < 0) { _selectedItem += _expandandedItems.Length; } } else if (key == ConsoleKey.RightArrow) { _selectedItem += _lastRenderNumRows; // check for overflow if (_selectedItem >= _expandandedItems.Length) { _selectedItem -= _expandandedItems.Length; } } return true; } public void Start(string prefix) { Running = true; if (!_abortedOrAccepted && prefix.Equals(GetExpandedCommand())) { return; } _abortedOrAccepted = false; if (prefix == null) { prefix = ""; // just in case } // split the last (quoted) word from the whole prefix as the soft/replacable prefix int splitPos = prefix.LastUnquotedIndexOf(' ') + 1; _hardPrefix = prefix.Substring(0, splitPos); _softPrefix = prefix.Substring(splitPos); _selectedItem = NOT_INITIALIZED; _userWasAsked = false; } public void Accept() { // finished _abortedOrAccepted = true; Running = false; } public void ChooseNext() { bool selectNextItem = true; if (_selectedItem == ASKING_USER) { _userWasAsked = true; } else if (_selectedItem == NOT_INITIALIZED) { if (TabExpansionEvent == null) { _expandandedItems = new string[] { }; return; } _expandandedItems = TabExpansionEvent(_hardPrefix, _softPrefix); _selectedItem = NO_ITEM_SELECTED; selectNextItem = false; } if (_expandandedItems == null || _expandandedItems.Length < 1) { return; } else if (_expandandedItems.Length == 1) { _selectedItem = 0; Accept(); return; } else if (selectNextItem) { _selectedItem++; _selectedItem = _selectedItem % _expandandedItems.Length; } } public void Abort(bool resetSelection) { Running = false; if (resetSelection) { _abortedOrAccepted = true; _selectedItem = NOT_INITIALIZED; } } public string GetExpandedCommand() { string chosenPrefix; if (_selectedItem < NO_ITEM_SELECTED) { chosenPrefix = _softPrefix; } else if (_selectedItem == NO_ITEM_SELECTED) { chosenPrefix = GetCommonPrefix(); } else { chosenPrefix = _expandandedItems[_selectedItem]; } return _hardPrefix + chosenPrefix; } public void Render(int startX, int startY) { RenderStartX = startX; RenderStartY = startY; int bufferWidth = Console.BufferWidth; int bufferHeight = Console.BufferHeight; int numItems = _expandandedItems == null ? 0 : _expandandedItems.Length; Clear(); if (numItems == 0 || !Running) { return; } int colwidth = _expandandedItems.Max(item => item.Length) + 2; if (colwidth >= bufferWidth) { colwidth = bufferWidth - 1; } int cols = bufferWidth / colwidth; cols = cols > 0 ? cols : 1; int rows = numItems / cols; rows = numItems % cols == 0 ? rows : rows + 1; // Check if we have too many items and need to ask the user if (_selectedItem == NO_ITEM_SELECTED && rows > Console.BufferHeight / 4 * 3 && !_userWasAsked) { string msg = String.Format("Want to see all {0} items in {1} lines? [Enter/Escape]", numItems, rows); WriteAt(0, RenderStartY + 1, msg, -1); _selectedItem = ASKING_USER; return; } WriteAt(RenderStartX, RenderStartY, GetExpandedCommand(), -1); int linesWithShownCommand = _maxWrittenY + 1 - RenderStartY; int showItemsOnLine = RenderStartY + linesWithShownCommand; if (numItems == 1) { return; } _lastRenderNumRows = rows; // print items // if we have more items than we can show, we need to calculate the scroll position int startShowRow = 0; int numShownLines = rows; int maxItemLines = bufferHeight - linesWithShownCommand; int selectionInLine = _selectedItem % rows; if (selectionInLine >= maxItemLines - linesWithShownCommand) { startShowRow = selectionInLine - maxItemLines + 1; numShownLines = rows - startShowRow; } numShownLines = numShownLines > maxItemLines ? maxItemLines : numShownLines; int lastShownLine = numShownLines + startShowRow -1; // scroll buffer, adjust start position int scroll = MakeSureTextFitsInBuffer(showItemsOnLine + numShownLines, ""); showItemsOnLine -= scroll; // now show items for (int i = 0; i < numItems; i++) { int col = i / rows; int row = i % rows; if (row < startShowRow || row > lastShownLine) { continue; } row -= startShowRow; // adjust row to relative row shown bool highlight = i == _selectedItem; WriteAt(col * colwidth, row + showItemsOnLine, _expandandedItems[i], colwidth -1, highlight); } } private void Clear() { if (_maxWrittenX <= RenderStartX && _maxWrittenY <= RenderStartY) { return; } int buffWidth = Console.BufferWidth; Console.SetCursorPosition(RenderStartX, RenderStartY); Console.Write("".PadLeft(buffWidth - RenderStartX)); for (int i = 0; i < _maxWrittenY - RenderStartY; i++) { Console.SetCursorPosition(0, RenderStartY + i + 1); Console.Write("".PadLeft(buffWidth)); } Console.SetCursorPosition(RenderStartX, RenderStartY); _maxWrittenX = RenderStartX; _maxWrittenY = RenderStartY; } private string GetCommonPrefix() { var commonPrefix = new StringBuilder(); if (_expandandedItems.Length < 1) { return _softPrefix; } for (int charIdx = 0; ; charIdx++) { if (charIdx >= _expandandedItems[0].Length) { break; } char curChar = _expandandedItems[0][charIdx]; bool doBreak = false; for (int i = 1; i < _expandandedItems.Length; i++) { if (charIdx >= _expandandedItems[i].Length || _expandandedItems[i][charIdx] != curChar) { doBreak = true; break; } } if (doBreak) { break; } commonPrefix.Append(curChar); } return commonPrefix.Length > 0 ? commonPrefix.ToString() : _softPrefix; } private int MakeSureTextFitsInBuffer(int theoreticalPos, string str) { int buffHeight = Console.BufferHeight; int buffWidth = Console.BufferWidth; int endPos = theoreticalPos + str.Length / buffWidth + 1; if (endPos < buffHeight) { return 0; } // TODO: check for auto-scrolling if cursor is in last line int doScroll = endPos - buffHeight; doScroll = doScroll > Console.CursorTop ? Console.CursorTop : doScroll; //limit to be able to reset cursor int resetCursorX = Console.CursorLeft; int resetCursorY = Console.CursorTop - doScroll; SaveSetCursorPosition(buffWidth - 1, buffHeight - 1); for (int i = 0; i < doScroll; i++) { Console.WriteLine(); } SaveSetCursorPosition(resetCursorX, resetCursorY); RenderStartY -= doScroll; _maxWrittenY -= doScroll; return doScroll; } private void WriteAt(int posX, int posY, string text, int maxWidth) { WriteAt(posX, posY, text, maxWidth, false); } private void WriteAt(int posX, int posY, string text, int maxWidth, bool colorInverse) { // backups int cursorX = Console.CursorLeft; int cursorY = Console.CursorTop; ConsoleColor fgColor = Console.ForegroundColor; ConsoleColor bgColor = Console.BackgroundColor; // scroll buffer string adjustToText = maxWidth < 0 ? text : ""; int scrolledLines = MakeSureTextFitsInBuffer(posY, adjustToText); posY -= scrolledLines; cursorY -= scrolledLines; // actual write if (colorInverse) { Console.ForegroundColor = bgColor; Console.BackgroundColor = fgColor; } SaveSetCursorPosition(posX, posY); string writeText = maxWidth < 0 ? text : FittedText(text, maxWidth); // -1 is line end Console.Write(writeText); _maxWrittenX = Console.CursorLeft > _maxWrittenX ? Console.CursorLeft : _maxWrittenX; _maxWrittenY = Console.CursorTop > _maxWrittenY ? Console.CursorTop : _maxWrittenY; // reset if (colorInverse) { Console.ForegroundColor = fgColor; Console.BackgroundColor = bgColor; } SaveSetCursorPosition(cursorX, cursorY); } private void SaveSetCursorPosition(int x, int y) { x = x < 0 ? 0 : x; x = x >= Console.BufferWidth ? Console.BufferWidth - 1 : x; y = y < 0 ? 0 : y; y = y >= Console.BufferHeight ? Console.BufferHeight - 1 : y; Console.SetCursorPosition(x, y); } private string FittedText(string text, int width) { if (width < 1) { throw new Exception("Invalid Bufer width!"); } if (width <= 3) { return "".PadRight(width, '.'); } if (text.Length <= width) { return text.PadRight(width); } return text.Substring(0, width - 3) + "..."; } } }
using System; using InAudioSystem.ExtensionMethods; using InAudioSystem.Internal; using InAudioSystem.TreeDrawer; using UnityEditor; using UnityEngine; namespace InAudioSystem.InAudioEditor { public class MusicCreatorGUI : BaseCreatorGUI<InMusicNode> { public MusicCreatorGUI(InMusicWindow window) : base(window) { this.window = window; } private int leftWidth; private int height; public bool OnGUI(int leftWidth, int height) { BaseOnGUI(); this.leftWidth = leftWidth; this.height = height; EditorGUIHelper.DrawColums(DrawLeftSide, DrawRightSide); return isDirty; } private void DrawLeftSide(Rect area) { Rect treeArea = EditorGUILayout.BeginVertical(GUILayout.Width(leftWidth), GUILayout.Height(height)); DrawSearchBar(); EditorGUILayout.BeginVertical(); isDirty |= treeDrawer.DrawTree(InAudioInstanceFinder.DataManager.MusicTree, treeArea); SelectedNode = treeDrawer.SelectedNode; EditorGUILayout.EndVertical(); EditorGUILayout.EndVertical(); } private void DrawRightSide(Rect area) { EditorGUILayout.BeginVertical(); if (SelectedNode != null) { DrawTypeControls(SelectedNode); EditorGUILayout.Separator(); EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); GUI.enabled = true; EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndVertical(); } private void DrawTypeControls(InMusicNode node) { try { var type = node._type; switch (type) { case MusicNodeType.Music: MusicGroupDrawer.Draw(node as InMusicGroup); break; case MusicNodeType.Folder: MusicFolderDrawer.Draw(node as InMusicFolder); break; case MusicNodeType.Root: MusicFolderDrawer.Draw(node as InMusicFolder); break; } } catch (ExitGUIException e) { throw e; } catch (ArgumentException e) { throw e; } /*catch (Exception e) { //While this catch was made to catch persistent errors, like a missing null check, it can also catch other errors EditorGUILayout.BeginVertical(); EditorGUILayout.HelpBox("An exception is getting caught while trying to draw node. ", MessageType.Error, true); if (GUILayout.Button("Create new element", GUILayout.Width(150))) { AudioNodeWorker.AddDataClass(node); } EditorGUILayout.TextArea(e.ToString()); EditorGUILayout.EndVertical(); }*/ } protected override bool CanDropObjects(InMusicNode node, UnityEngine.Object[] objects) { if (node == null || objects == null || objects.Length == 0) return false; var obj = objects[0]; var dragged = obj as InMusicNode; if (dragged != null) { if (dragged.IsRoot || dragged == node || TreeWalker.IsParentOf(dragged, node)) return false; if (!node.IsRootOrFolder && dragged.IsRootOrFolder) return false; return true; } else if(node._type == MusicNodeType.Music) { var clips = objects.Convert(o => o as AudioClip).TakeNonNulls(); if (clips.Length > 0) { return true; } } return false; } protected override void OnDrop(InMusicNode newParent, UnityEngine.Object[] objects) { if (newParent == null || objects == null ) return; var dragged = objects[0] as InMusicNode; if (dragged != null) { if (dragged.IsRoot || dragged == newParent) return; InUndoHelper.DoInGroup(() => { if (dragged.gameObject != newParent.gameObject) { if (EditorUtility.DisplayDialog("Move?", "Warning, this will break all external references to this and all child nodes!\n" + "Move node from\"" + dragged.gameObject.name + "\" to \"" + newParent.gameObject.name + "\"?", "Ok", "Cancel")) { treeDrawer.SelectedNode = TreeWalker.GetPreviousVisibleNode(treeDrawer.SelectedNode); MusicWorker.Duplicate(newParent.gameObject, dragged, newParent); DeleteNodeRec(dragged); } } else { var oldParent = dragged._parent; InUndoHelper.RecordObjects("Music drag-n-drop", dragged, oldParent, newParent); dragged.MoveToNewParent(newParent); newParent.EditorSettings.IsFoldedOut = true; } Event.current.UseEvent(); }); } else if (newParent._type == MusicNodeType.Music) { var clips = objects.Convert(o => o as AudioClip).TakeNonNulls(); var musicGroup = newParent as InMusicGroup; if (musicGroup != null) { InUndoHelper.DoInGroup(() => { InUndoHelper.RecordObject(newParent,"Music Clip Add"); foreach (var audioClip in clips) { musicGroup._clips.Add(audioClip); } }); } } } protected override void OnContext(InMusicNode node) { var menu = new GenericMenu(); menu.AddDisabledItem(new GUIContent(node._name)); menu.AddSeparator(""); if (node.IsRootOrFolder) { menu.AddItem(new GUIContent("Create Folder"), false, () => CreateFolder(node)); menu.AddItem(new GUIContent("Create Music Group"), false, () => CreateMusicGroup(node)); } else { menu.AddDisabledItem(new GUIContent("Create Folder")); menu.AddItem(new GUIContent("Create Music Group"), false, () => CreateMusicGroup(node)); } menu.AddSeparator(""); #region Send to event if (node.IsRootOrFolder) { menu.AddItem(new GUIContent("Create child folder in new prefab"), false, obj => { CreateFolderInNewPrefab(node); }, node); } #endregion #region Send to event if (!node.IsRootOrFolder) { menu.AddItem(new GUIContent("Send to Event Window"), false, () => EventWindow.Launch().ReceiveNode(node as InMusicGroup)); } else { menu.AddDisabledItem(new GUIContent("Send to Event Window")); } #endregion menu.AddSeparator(""); if (node.IsRoot) { menu.AddDisabledItem(new GUIContent("Delete")); } else { menu.AddItem(new GUIContent("Delete"), false, ()=> DeleteNode(node) ); } menu.ShowAsContext(); } private void DeleteNode(InMusicNode toDelete) { InUndoHelper.DoInGroup(() => DeleteNodeRec(toDelete)); } private void CreateFolderInNewPrefab(InMusicNode parent) { InAudioWindowOpener.ShowNewDataWindow((gameObject => { var node = MusicWorker.CreateFolder(gameObject, parent); node._name += " (External)"; node._externalPlacement = true; })); } private void DeleteNodeRec(InMusicNode toDelete) { for (int i = 0; i < toDelete._children.Count; i++) { DeleteNodeRec(toDelete._children[i]); } InUndoHelper.Destroy(toDelete); } private void CreateFolder(InMusicNode parent) { InUndoHelper.DoInGroup(() => { InUndoHelper.RecordObjectFull(parent, "Create Music Folder"); parent.EditorSettings.IsFoldedOut = true; MusicWorker.CreateFolder(parent.gameObject, parent); }); } private void CreateMusicGroup(InMusicNode parent) { InUndoHelper.DoInGroup(() => { InUndoHelper.RecordObjectFull(parent, "Create Music Folder"); parent.EditorSettings.IsFoldedOut = true; MusicWorker.CreateMusicGroup(parent); }); } public override void OnEnable() { treeDrawer.Filter(n => false); treeDrawer.OnNodeDraw = MusicDrawer.Draw; treeDrawer.OnContext = OnContext; treeDrawer.CanDropObjects = CanDropObjects; treeDrawer.OnDrop = OnDrop; } protected override bool OnNodeDraw(InMusicNode node, bool isSelected, out bool clicked) { return GenericTreeNodeDrawer.Draw(node, isSelected, out clicked); } internal void FindAudio(Func<InMusicNode, bool> filter) { searchingFor = "Finding nodes"; lowercaseSearchingFor = "Finding nodes"; treeDrawer.Filter(filter); } protected override InMusicNode Root() { if (InAudioInstanceFinder.DataManager == null) { return null; } return InAudioInstanceFinder.DataManager.MusicTree; } protected override GUIPrefs GUIData { get { if (InAudioInstanceFinder.InAudioGuiUserPrefs != null) return InAudioInstanceFinder.InAudioGuiUserPrefs.MusicGUIData; else return null; } } } }
using System.Collections.Generic; using NUnit.Framework; // ReSharper disable InconsistentNaming namespace SSCases.TestCases { public class A { private static readonly Case[] _allCases = { new EMPTY(), new PATTERN(), new ___________________________________________________________________________________(), new ______________________________________________________________A(), new __________________________________A____________________________(), new _________A________________A__________A____________A______A__________AA(), new A______________________________________________________________(), new A_A___AAAA____AAA____AAA___AAAAAAAAAAAAAAAAAAAAAAAAAAAAA(), new AAAA_________A___AAAA______A__________A________AAAAA____A______A__________AA(), new aaaaaaA(), new Aaaaaaaaaaaa(), new AAAAAAAAAAAAA(), new AaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaA(), new Afajfchdsfjksakk(), new ashfdhasfdhasfdhgsafdhgasfdhfashdfhgsafdgas236824e87326ehqshhjzjhxjjxzjhxgjhz(), new B(), new Bgg(), new BggdsdfdsffsJKKLKLDsskksd(), new fajfchdsfjksakkA(), new fajfchdsfjksakkAfajfchdsfjksakk(), new hdghsjdhaksjdhakjshdkjashdjkhskjdhaskjdhskjshdjkashdjkashdjkhasjdhaj(), new hjhjhjhjhjhjhjhjhjhjhjhjhjjhjAAAAAAAAAAAAAAAAAAAAajhjhjhjhjhjhjhAAAAAAAAAAAAAA(), new hsdghAdskhdjAAdhsjhdA(), new tttttttttAAAAAtdbndjsgdhAAadjgsjdgAAAdjhsgdhsgdAAAAjsdjsjAAA(), new weyiruyweiiryweiuyrieuwyriuewyriuweyriuweyiuewyruieyriuweeyuryewwiyeiur(), }; public static IEnumerable<Case> AllCases { get { return _allCases; } } public static IEnumerable<TestCaseData> AllCasesForExists { get { return HelpExtensions.SelectCasesForExistsFrom(_allCases); } } public static IEnumerable<TestCaseData> AllCasesForFirst { get { return HelpExtensions.SelectCasesForFindFirstFrom(_allCases); } } public static IEnumerable<TestCaseData> AllCasesForFindLast { get { return HelpExtensions.SelectCasesForFindLastFrom(_allCases); } } public static IEnumerable<TestCaseData> AllCasesForFindAll { get { return HelpExtensions.SelectCasesForFindAllFrom(_allCases); } } public class EMPTY : Case { public EMPTY() : base("A", "", ExpectedResult.NotFound) { } } public class PATTERN : Case { public PATTERN() : base("A", "A", new ExpectedResult(true, 0, 0, new[] { 0 })) { } } public class ___________________________________________________________________________________ : Case { public ___________________________________________________________________________________() : base("A", "___________________________________________________________________________________", ExpectedResult.NotFound) { } } public class ______________________________________________________________A : Case { public ______________________________________________________________A() : base("A", "______________________________________________________________A", new ExpectedResult(true, 62, 62, new[] { 62 })) { } } public class __________________________________A____________________________ : Case { public __________________________________A____________________________() : base("A", "__________________________________A____________________________", new ExpectedResult(true, 34, 34, new[] { 34 })) { } } public class _________A________________A__________A____________A______A__________AA : Case { public _________A________________A__________A____________A______A__________AA() : base("A", "_________A________________A__________A____________A______A__________AA", new ExpectedResult(true, 9, 69, new[] { 9, 26, 37, 50, 57, 68, 69 })) { } } public class A______________________________________________________________ : Case { public A______________________________________________________________() : base("A", "A______________________________________________________________", new ExpectedResult(true, 0, 0, new[] { 0 })) { } } public class A_A___AAAA____AAA____AAA___AAAAAAAAAAAAAAAAAAAAAAAAAAAAA : Case { public A_A___AAAA____AAA____AAA___AAAAAAAAAAAAAAAAAAAAAAAAAAAAA() : base("A", "A_A___AAAA____AAA____AAA___AAAAAAAAAAAAAAAAAAAAAAAAAAAAA", new ExpectedResult(true, 0, 55, new[] { 0, 2, 6, 7, 8, 9, 14, 15, 16, 21, 22, 23, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55 })) { } } public class AAAA_________A___AAAA______A__________A________AAAAA____A______A__________AA : Case { public AAAA_________A___AAAA______A__________A________AAAAA____A______A__________AA() : base("A", "AAAA_________A___AAAA______A__________A________AAAAA____A______A__________AA", new ExpectedResult(true, 0, 75, new[] { 0, 1, 2, 3, 13, 17, 18, 19, 20, 27, 38, 47, 48, 49, 50, 51, 56, 63, 74, 75 })) { } } public class aaaaaaA : Case { public aaaaaaA() : base("A", "aaaaaaA", new ExpectedResult(true, 6, 6, new[] { 6 })) { } } public class Aaaaaaaaaaaa : Case { public Aaaaaaaaaaaa() : base("A", "Aaaaaaaaaaaa", new ExpectedResult(true, 0, 0, new[] { 0 })) { } } public class AAAAAAAAAAAAA : Case { public AAAAAAAAAAAAA() : base("A", "AAAAAAAAAAAAA", new ExpectedResult(true, 0, 12, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 })) { } } public class AaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaA : Case { public AaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaA() : base("A", "AaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaA", new ExpectedResult(true, 0, 48, new[] { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48 })) { } } public class Afajfchdsfjksakk : Case { public Afajfchdsfjksakk() : base("A", "Afajfchdsfjksakk", new ExpectedResult(true, 0, 0, new[] { 0 })) { } } public class ashfdhasfdhasfdhgsafdhgasfdhfashdfhgsafdgas236824e87326ehqshhjzjhxjjxzjhxgjhz : Case { public ashfdhasfdhasfdhgsafdhgasfdhfashdfhgsafdgas236824e87326ehqshhjzjhxjjxzjhxgjhz() : base("A", "ashfdhasfdhasfdhgsafdhgasfdhfashdfhgsafdgas236824e87326ehqshhjzjhxjjxzjhxgjhz", ExpectedResult.NotFound) { } } public class B : Case { public B() : base("A", "B", ExpectedResult.NotFound) { } } public class Bgg : Case { public Bgg() : base("A", "Bgg", ExpectedResult.NotFound) { } } public class BggdsdfdsffsJKKLKLDsskksd : Case { public BggdsdfdsffsJKKLKLDsskksd() : base("A", "BggdsdfdsffsJKKLKLDsskksd", ExpectedResult.NotFound) { } } public class fajfchdsfjksakkA : Case { public fajfchdsfjksakkA() : base("A", "fajfchdsfjksakkA", new ExpectedResult(true, 15, 15, new[] { 15 })) { } } public class fajfchdsfjksakkAfajfchdsfjksakk : Case { public fajfchdsfjksakkAfajfchdsfjksakk() : base("A", "fajfchdsfjksakkAfajfchdsfjksakk", new ExpectedResult(true, 15, 15, new[] { 15 })) { } } public class hdghsjdhaksjdhakjshdkjashdjkhskjdhaskjdhskjshdjkashdjkashdjkhasjdhaj : Case { public hdghsjdhaksjdhakjshdkjashdjkhskjdhaskjdhskjshdjkashdjkashdjkhasjdhaj() : base("A", "hdghsjdhaksjdhakjshdkjashdjkhskjdhaskjdhskjshdjkashdjkashdjkhasjdhaj", ExpectedResult.NotFound) { } } public class hjhjhjhjhjhjhjhjhjhjhjhjhjjhjAAAAAAAAAAAAAAAAAAAAajhjhjhjhjhjhjhAAAAAAAAAAAAAA : Case { public hjhjhjhjhjhjhjhjhjhjhjhjhjjhjAAAAAAAAAAAAAAAAAAAAajhjhjhjhjhjhjhAAAAAAAAAAAAAA() : base("A", "hjhjhjhjhjhjhjhjhjhjhjhjhjjhjAAAAAAAAAAAAAAAAAAAAajhjhjhjhjhjhjhAAAAAAAAAAAAAA", new ExpectedResult(true, 29, 77, new[] { 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77 })) { } } public class hsdghAdskhdjAAdhsjhdA : Case { public hsdghAdskhdjAAdhsjhdA() : base("A", "hsdghAdskhdjAAdhsjhdA", new ExpectedResult(true, 5, 20, new[] { 5, 12, 13, 20 })) { } } public class tttttttttAAAAAtdbndjsgdhAAadjgsjdgAAAdjhsgdhsgdAAAAjsdjsjAAA : Case { public tttttttttAAAAAtdbndjsgdhAAadjgsjdgAAAdjhsgdhsgdAAAAjsdjsjAAA() : base("A", "tttttttttAAAAAtdbndjsgdhAAadjgsjdgAAAdjhsgdhsgdAAAAjsdjsjAAA", new ExpectedResult(true, 9, 59, new[] { 9, 10, 11, 12, 13, 24, 25, 34, 35, 36, 47, 48, 49, 50, 57, 58, 59 })) { } } public class weyiruyweiiryweiuyrieuwyriuewyriuweyriuweyiuewyruieyriuweeyuryewwiyeiur : Case { public weyiruyweiiryweiuyrieuwyriuewyriuweyriuweyiuewyruieyriuweeyuryewwiyeiur() : base("A", "weyiruyweiiryweiuyrieuwyriuewyriuweyriuweyiuewyruieyriuweeyuryewwiyeiur", ExpectedResult.NotFound) { } } } }
// This is a copy of the 7-zip LZMA // compression library. using System; namespace LZMA { using RangeCoder; internal class LzmaDecoder : ICoder, ISetDecoderProperties // ,System.IO.Stream { class LenDecoder { BitDecoder m_Choice = new BitDecoder(); BitDecoder m_Choice2 = new BitDecoder(); BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); uint m_NumPosStates = 0; public void Create(uint numPosStates) { for (uint posState = m_NumPosStates; posState < numPosStates; posState++) { m_LowCoder[posState] = new BitTreeDecoder(Base.kNumLowLenBits); m_MidCoder[posState] = new BitTreeDecoder(Base.kNumMidLenBits); } m_NumPosStates = numPosStates; } public void Init() { m_Choice.Init(); for (uint posState = 0; posState < m_NumPosStates; posState++) { m_LowCoder[posState].Init(); m_MidCoder[posState].Init(); } m_Choice2.Init(); m_HighCoder.Init(); } public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState) { if (m_Choice.Decode(rangeDecoder) == 0) return m_LowCoder[posState].Decode(rangeDecoder); else { uint symbol = Base.kNumLowLenSymbols; if (m_Choice2.Decode(rangeDecoder) == 0) symbol += m_MidCoder[posState].Decode(rangeDecoder); else { symbol += Base.kNumMidLenSymbols; symbol += m_HighCoder.Decode(rangeDecoder); } return symbol; } } } class LiteralDecoder { struct Decoder2 { BitDecoder[] m_Decoders; public void Create() { m_Decoders = new BitDecoder[0x300]; } public void Init() { for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); } public byte DecodeNormal(RangeCoder.Decoder rangeDecoder) { uint symbol = 1; do symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); while (symbol < 0x100); return (byte)symbol; } public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte) { uint symbol = 1; do { uint matchBit = (uint)(matchByte >> 7) & 1; matchByte <<= 1; uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder); symbol = (symbol << 1) | bit; if (matchBit != bit) { while (symbol < 0x100) symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); break; } } while (symbol < 0x100); return (byte)symbol; } } Decoder2[] m_Coders; int m_NumPrevBits; int m_NumPosBits; uint m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = ((uint)1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Decoder2[numStates]; for (uint i = 0; i < numStates; i++) m_Coders[i].Create(); } public void Init() { uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); for (uint i = 0; i < numStates; i++) m_Coders[i].Init(); } uint GetState(uint pos, byte prevByte) { return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); } public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte) { return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); } public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte) { return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); } }; OutWindow m_OutWindow = new OutWindow(); RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder(); BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); LenDecoder m_LenDecoder = new LenDecoder(); LenDecoder m_RepLenDecoder = new LenDecoder(); LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); uint m_DictionarySize; uint m_DictionarySizeCheck; uint m_PosStateMask; public LzmaDecoder() { m_DictionarySize = 0xFFFFFFFF; for (int i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); } void SetDictionarySize(uint dictionarySize) { if (m_DictionarySize != dictionarySize) { m_DictionarySize = dictionarySize; m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1); uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12)); m_OutWindow.Create(blockSize); } } void SetLiteralProperties(int lp, int lc) { if (lp > 8) throw new InvalidParamException(); if (lc > 8) throw new InvalidParamException(); m_LiteralDecoder.Create(lp, lc); } void SetPosBitsProperties(int pb) { if (pb > Base.kNumPosStatesBitsMax) throw new InvalidParamException(); uint numPosStates = (uint)1 << pb; m_LenDecoder.Create(numPosStates); m_RepLenDecoder.Create(numPosStates); m_PosStateMask = numPosStates - 1; } bool _solid = false; void Init(System.IO.Stream inStream, System.IO.Stream outStream) { m_RangeDecoder.Init(inStream); m_OutWindow.Init(outStream, _solid); uint i; for (i = 0; i < Base.kNumStates; i++) { for (uint j = 0; j <= m_PosStateMask; j++) { uint index = (i << Base.kNumPosStatesBitsMax) + j; m_IsMatchDecoders[index].Init(); m_IsRep0LongDecoders[index].Init(); } m_IsRepDecoders[i].Init(); m_IsRepG0Decoders[i].Init(); m_IsRepG1Decoders[i].Init(); m_IsRepG2Decoders[i].Init(); } m_LiteralDecoder.Init(); for (i = 0; i < Base.kNumLenToPosStates; i++) m_PosSlotDecoder[i].Init(); // m_PosSpecDecoder.Init(); for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) m_PosDecoders[i].Init(); m_LenDecoder.Init(); m_RepLenDecoder.Init(); m_PosAlignDecoder.Init(); } public void Code(System.IO.Stream inStream, System.IO.Stream outStream, Int64 inSize, Int64 outSize, ICodeProgress progress) { Init(inStream, outStream); Base.State state = new Base.State(); state.Init(); uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; UInt64 nowPos64 = 0; UInt64 outSize64 = (UInt64)outSize; if (nowPos64 < outSize64) { if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0) throw new DataErrorException(); state.UpdateChar(); byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0); m_OutWindow.PutByte(b); nowPos64++; } while (nowPos64 < outSize64) { // UInt64 next = Math.Min(nowPos64 + (1 << 18), outSize64); // while(nowPos64 < next) { uint posState = (uint)nowPos64 & m_PosStateMask; if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) { byte b; byte prevByte = m_OutWindow.GetByte(0); if (!state.IsCharState()) b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder, (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0)); else b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte); m_OutWindow.PutByte(b); state.UpdateChar(); nowPos64++; } else { uint len; if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1) { if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0) { if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) { state.UpdateShortRep(); m_OutWindow.PutByte(m_OutWindow.GetByte(rep0)); nowPos64++; continue; } } else { UInt32 distance; if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0) { distance = rep1; } else { if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0) distance = rep2; else { distance = rep3; rep3 = rep2; } rep2 = rep1; } rep1 = rep0; rep0 = distance; } len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; state.UpdateRep(); } else { rep3 = rep2; rep2 = rep1; rep1 = rep0; len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); state.UpdateMatch(); uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); if (posSlot >= Base.kStartPosModelIndex) { int numDirectBits = (int)((posSlot >> 1) - 1); rep0 = ((2 | (posSlot & 1)) << numDirectBits); if (posSlot < Base.kEndPosModelIndex) rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); else { rep0 += (m_RangeDecoder.DecodeDirectBits( numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); } } else rep0 = posSlot; } if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck) { if (rep0 == 0xFFFFFFFF) break; throw new DataErrorException(); } m_OutWindow.CopyBlock(rep0, len); nowPos64 += len; } } } m_OutWindow.Flush(); m_OutWindow.ReleaseStream(); m_RangeDecoder.ReleaseStream(); } public void SetDecoderProperties(byte[] properties) { if (properties.Length < 5) throw new InvalidParamException(); int lc = properties[0] % 9; int remainder = properties[0] / 9; int lp = remainder % 5; int pb = remainder / 5; if (pb > Base.kNumPosStatesBitsMax) throw new InvalidParamException(); UInt32 dictionarySize = 0; for (int i = 0; i < 4; i++) dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8); SetDictionarySize(dictionarySize); SetLiteralProperties(lp, lc); SetPosBitsProperties(pb); } public bool Train(System.IO.Stream stream) { _solid = true; return m_OutWindow.Train(stream); } /* public override bool CanRead { get { return true; }} public override bool CanWrite { get { return true; }} public override bool CanSeek { get { return true; }} public override long Length { get { return 0; }} public override long Position { get { return 0; } set { } } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override void Write(byte[] buffer, int offset, int count) { } public override long Seek(long offset, System.IO.SeekOrigin origin) { return 0; } public override void SetLength(long value) {} */ } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TakeOrSkipWhileQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Threading; using System.Diagnostics.Contracts; namespace System.Linq.Parallel { /// <summary> /// Take- and SkipWhile work similarly. Execution is broken into two phases: Search /// and Yield. /// /// During the Search phase, many partitions at once search for the first occurrence /// of a false element. As they search, any time a partition finds a false element /// whose index is lesser than the current lowest-known false element, the new index /// will be published, so other partitions can stop the search. The search stops /// as soon as (1) a partition exhausts its input, (2) the predicate yields false for /// one of the partition's elements, or (3) its input index passes the current lowest- /// known index (sufficient since a given partition's indices are always strictly /// incrementing -- asserted below). Elements are buffered during this process. /// /// Partitions use a barrier after Search and before moving on to Yield. Once all /// have passed the barrier, Yielding begins. At this point, the lowest-known false /// index will be accurate for the entire set, since all partitions have finished /// scanning. This is where TakeWhile and SkipWhile differ. TakeWhile will start at /// the beginning of its buffer and yield all elements whose indices are less than /// the lowest-known false index. SkipWhile, on the other hand, will skipp any such /// elements in the buffer, yielding those whose index is greater than or equal to /// the lowest-known false index, and then finish yielding any remaining elements in /// its data source (since it may have stopped prematurely due to (3) above). /// </summary> /// <typeparam name="TResult"></typeparam> internal sealed class TakeOrSkipWhileQueryOperator<TResult> : UnaryQueryOperator<TResult, TResult> { // Predicate function used to decide when to stop yielding elements. One pair is used for // index-based evaluation (i.e. it is passed the index as well as the element's value). private Func<TResult, bool> _predicate; private Func<TResult, int, bool> _indexedPredicate; private readonly bool _take; // Whether to take (true) or skip (false). private bool _prematureMerge = false; // Whether to prematurely merge the input of this operator. private bool _limitsParallelism = false; // The precomputed value of LimitsParallelism //--------------------------------------------------------------------------------------- // Initializes a new take-while operator. // // Arguments: // child - the child data source to enumerate // predicate - the predicate function (if expression tree isn't provided) // indexedPredicate - the index-based predicate function (if expression tree isn't provided) // take - whether this is a TakeWhile (true) or SkipWhile (false) // // Notes: // Only one kind of predicate can be specified, an index-based one or not. If an // expression tree is provided, the delegate cannot also be provided. // internal TakeOrSkipWhileQueryOperator(IEnumerable<TResult> child, Func<TResult, bool> predicate, Func<TResult, int, bool> indexedPredicate, bool take) : base(child) { Contract.Assert(child != null, "child data source cannot be null"); Contract.Assert(predicate != null || indexedPredicate != null, "need a predicate function"); _predicate = predicate; _indexedPredicate = indexedPredicate; _take = take; InitOrderIndexState(); } /// <summary> /// Determines the order index state for the output operator /// </summary> private void InitOrderIndexState() { // SkipWhile/TakeWhile needs an increasing index. However, if the predicate expression depends on the index, // the index needs to be correct, not just increasing. OrdinalIndexState requiredIndexState = OrdinalIndexState.Increasing; OrdinalIndexState childIndexState = Child.OrdinalIndexState; if (_indexedPredicate != null) { requiredIndexState = OrdinalIndexState.Correct; _limitsParallelism = childIndexState == OrdinalIndexState.Increasing; } OrdinalIndexState indexState = ExchangeUtilities.Worse(childIndexState, OrdinalIndexState.Correct); if (indexState.IsWorseThan(requiredIndexState)) { _prematureMerge = true; } if (!_take) { // If the index was correct, now it is only increasing. indexState = indexState.Worse(OrdinalIndexState.Increasing); } SetOrdinalIndexState(indexState); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TResult, TKey> inputStream, IPartitionedStreamRecipient<TResult> recipient, bool preferStriping, QuerySettings settings) { if (_prematureMerge) { ListQueryResults<TResult> results = ExecuteAndCollectResults(inputStream, inputStream.PartitionCount, Child.OutputOrdered, preferStriping, settings); PartitionedStream<TResult, int> listInputStream = results.GetPartitionedStream(); WrapHelper<int>(listInputStream, recipient, settings); } else { WrapHelper<TKey>(inputStream, recipient, settings); } } private void WrapHelper<TKey>(PartitionedStream<TResult, TKey> inputStream, IPartitionedStreamRecipient<TResult> recipient, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; // Create shared data. OperatorState<TKey> operatorState = new OperatorState<TKey>(); CountdownEvent sharedBarrier = new CountdownEvent(partitionCount); Contract.Assert(_indexedPredicate == null || typeof(TKey) == typeof(int)); Func<TResult, TKey, bool> convertedIndexedPredicate = (Func<TResult, TKey, bool>)(object)_indexedPredicate; PartitionedStream<TResult, TKey> partitionedStream = new PartitionedStream<TResult, TKey>(partitionCount, inputStream.KeyComparer, OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { partitionedStream[i] = new TakeOrSkipWhileQueryOperatorEnumerator<TKey>( inputStream[i], _predicate, convertedIndexedPredicate, _take, operatorState, sharedBarrier, settings.CancellationState.MergedCancellationToken, inputStream.KeyComparer); } recipient.Receive(partitionedStream); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TResult> Open(QuerySettings settings, bool preferStriping) { QueryResults<TResult> childQueryResults = Child.Open(settings, true); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TResult> AsSequentialQuery(CancellationToken token) { if (_take) { if (_indexedPredicate != null) { return Child.AsSequentialQuery(token).TakeWhile(_indexedPredicate); } return Child.AsSequentialQuery(token).TakeWhile(_predicate); } if (_indexedPredicate != null) { IEnumerable<TResult> wrappedIndexedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedIndexedChild.SkipWhile(_indexedPredicate); } IEnumerable<TResult> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedChild.SkipWhile(_predicate); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return _limitsParallelism; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for executing the take- or skip-while. // class TakeOrSkipWhileQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TResult, TKey> { private readonly QueryOperatorEnumerator<TResult, TKey> _source; // The data source to enumerate. private readonly Func<TResult, bool> _predicate; // The actual predicate function. private readonly Func<TResult, TKey, bool> _indexedPredicate; // The actual index-based predicate function. private readonly bool _take; // Whether to execute a take- (true) or skip-while (false). private readonly IComparer<TKey> _keyComparer; // Comparer for the order keys. // These fields are all shared among partitions. private readonly OperatorState<TKey> _operatorState; // The lowest false found by any partition. private readonly CountdownEvent _sharedBarrier; // To separate the search/yield phases. private readonly CancellationToken _cancellationToken; // Token used to cancel this operator. private List<Pair> _buffer; // Our buffer. private Shared<int> _bufferIndex; // Our current index within the buffer. [allocate in moveNext to avoid false-sharing] private int _updatesSeen; // How many updates has this enumerator observed? (Each other enumerator will contribute one update.) private TKey _currentLowKey; // The lowest key rejected by one of the other enumerators. //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal TakeOrSkipWhileQueryOperatorEnumerator( QueryOperatorEnumerator<TResult, TKey> source, Func<TResult, bool> predicate, Func<TResult, TKey, bool> indexedPredicate, bool take, OperatorState<TKey> operatorState, CountdownEvent sharedBarrier, CancellationToken cancelToken, IComparer<TKey> keyComparer) { Contract.Assert(source != null); Contract.Assert(predicate != null || indexedPredicate != null); Contract.Assert(operatorState != null); Contract.Assert(sharedBarrier != null); Contract.Assert(keyComparer != null); _source = source; _predicate = predicate; _indexedPredicate = indexedPredicate; _take = take; _operatorState = operatorState; _sharedBarrier = sharedBarrier; _cancellationToken = cancelToken; _keyComparer = keyComparer; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext(ref TResult currentElement, ref TKey currentKey) { // If the buffer has not been created, we will generate it lazily on demand. if (_buffer == null) { // Create a buffer, but don't publish it yet (in case of exception). List<Pair> buffer = new List<Pair>(); // Enter the search phase. In this phase, we scan the input until one of three // things happens: (1) all input has been exhausted, (2) the predicate yields // false for one of our elements, or (3) we move past the current lowest index // found by other partitions for a false element. As we go, we have to remember // the elements by placing them into the buffer. try { TResult current = default(TResult); TKey key = default(TKey); int i = 0; //counter to help with cancellation while (_source.MoveNext(ref current, ref key)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // Add the current element to our buffer. buffer.Add(new Pair(current, key)); // See if another partition has found a false value before this element. If so, // we should stop scanning the input now and reach the barrier ASAP. if (_updatesSeen != _operatorState._updatesDone) { lock (_operatorState) { _currentLowKey = _operatorState._currentLowKey; _updatesSeen = _operatorState._updatesDone; } } if (_updatesSeen > 0 && _keyComparer.Compare(key, _currentLowKey) > 0) { break; } // Evaluate the predicate, either indexed or not based on info passed to the ctor. bool predicateResult; if (_predicate != null) { predicateResult = _predicate(current); } else { Contract.Assert(_indexedPredicate != null); predicateResult = _indexedPredicate(current, key); } if (!predicateResult) { // Signal that we've found a false element, racing with other partitions to // set the shared index value. lock (_operatorState) { if (_operatorState._updatesDone == 0 || _keyComparer.Compare(_operatorState._currentLowKey, key) > 0) { _currentLowKey = _operatorState._currentLowKey = key; _updatesSeen = ++_operatorState._updatesDone; } } break; } } } finally { // No matter whether we exit due to an exception or normal completion, we must ensure // that we signal other partitions that we have completed. Otherwise, we can cause deadlocks. _sharedBarrier.Signal(); } // Before exiting the search phase, we will synchronize with others. This is a barrier. _sharedBarrier.Wait(_cancellationToken); // Publish the buffer and set the index to just before the 1st element. _buffer = buffer; _bufferIndex = new Shared<int>(-1); } // Now either enter (or continue) the yielding phase. As soon as we reach this, we know the // current shared "low false" value is the absolute lowest with a false. if (_take) { // In the case of a take-while, we will yield each element from our buffer for which // the element is lesser than the lowest false index found. if (_bufferIndex.Value >= _buffer.Count - 1) { return false; } // Increment the index, and remember the values. ++_bufferIndex.Value; currentElement = (TResult)_buffer[_bufferIndex.Value].First; currentKey = (TKey)_buffer[_bufferIndex.Value].Second; return _operatorState._updatesDone == 0 || _keyComparer.Compare(_operatorState._currentLowKey, currentKey) > 0; } else { // If no false was found, the output is empty. if (_operatorState._updatesDone == 0) { return false; } // In the case of a skip-while, we must skip over elements whose index is lesser than the // lowest index found. Once we've exhausted the buffer, we must go back and continue // enumerating the data source until it is empty. if (_bufferIndex.Value < _buffer.Count - 1) { for (_bufferIndex.Value++; _bufferIndex.Value < _buffer.Count; _bufferIndex.Value++) { // If the current buffered element's index is greater than or equal to the smallest // false index found, we will yield it as a result. if (_keyComparer.Compare((TKey)_buffer[_bufferIndex.Value].Second, _operatorState._currentLowKey) >= 0) { currentElement = (TResult)_buffer[_bufferIndex.Value].First; currentKey = (TKey)_buffer[_bufferIndex.Value].Second; return true; } } } // Lastly, so long as our input still has elements, they will be yieldable. if (_source.MoveNext(ref currentElement, ref currentKey)) { Contract.Assert(_keyComparer.Compare(currentKey, _operatorState._currentLowKey) > 0, "expected remaining element indices to be greater than smallest"); return true; } } return false; } protected override void Dispose(bool disposing) { _source.Dispose(); } } class OperatorState<TKey> { volatile internal int _updatesDone = 0; internal TKey _currentLowKey; } } }
// 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. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// How the Batch service should respond when a task completes. /// </summary> public partial class ExitConditions : ITransportObjectProvider<Models.ExitConditions>, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<ExitOptions> DefaultProperty; public readonly PropertyAccessor<IList<ExitCodeRangeMapping>> ExitCodeRangesProperty; public readonly PropertyAccessor<IList<ExitCodeMapping>> ExitCodesProperty; public readonly PropertyAccessor<ExitOptions> FileUploadErrorProperty; public readonly PropertyAccessor<ExitOptions> PreProcessingErrorProperty; public PropertyContainer() : base(BindingState.Unbound) { this.DefaultProperty = this.CreatePropertyAccessor<ExitOptions>("Default", BindingAccess.Read | BindingAccess.Write); this.ExitCodeRangesProperty = this.CreatePropertyAccessor<IList<ExitCodeRangeMapping>>("ExitCodeRanges", BindingAccess.Read | BindingAccess.Write); this.ExitCodesProperty = this.CreatePropertyAccessor<IList<ExitCodeMapping>>("ExitCodes", BindingAccess.Read | BindingAccess.Write); this.FileUploadErrorProperty = this.CreatePropertyAccessor<ExitOptions>("FileUploadError", BindingAccess.Read | BindingAccess.Write); this.PreProcessingErrorProperty = this.CreatePropertyAccessor<ExitOptions>("PreProcessingError", BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.ExitConditions protocolObject) : base(BindingState.Bound) { this.DefaultProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.DefaultProperty, o => new ExitOptions(o).Freeze()), "Default", BindingAccess.Read); this.ExitCodeRangesProperty = this.CreatePropertyAccessor( ExitCodeRangeMapping.ConvertFromProtocolCollectionAndFreeze(protocolObject.ExitCodeRanges), "ExitCodeRanges", BindingAccess.Read); this.ExitCodesProperty = this.CreatePropertyAccessor( ExitCodeMapping.ConvertFromProtocolCollectionAndFreeze(protocolObject.ExitCodes), "ExitCodes", BindingAccess.Read); this.FileUploadErrorProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.FileUploadError, o => new ExitOptions(o).Freeze()), "FileUploadError", BindingAccess.Read); this.PreProcessingErrorProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.PreProcessingError, o => new ExitOptions(o).Freeze()), "PreProcessingError", BindingAccess.Read); } } private readonly PropertyContainer propertyContainer; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ExitConditions"/> class. /// </summary> public ExitConditions() { this.propertyContainer = new PropertyContainer(); } internal ExitConditions(Models.ExitConditions protocolObject) { this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region ExitConditions /// <summary> /// Gets or sets how the Batch service should respond if the task fails with an exit condition not covered by any /// of the other properties. /// </summary> /// <remarks> /// This value is used if the task exits with any nonzero exit code not listed in the <see cref="ExitCodes"/> or /// <see cref="ExitCodeRanges"/> collection, with a preprocessing error if the <see cref="PreProcessingError"/> property /// is not present, or with a file upload failure if the <see cref="FileUploadError"/> property is not present. /// </remarks> public ExitOptions Default { get { return this.propertyContainer.DefaultProperty.Value; } set { this.propertyContainer.DefaultProperty.Value = value; } } /// <summary> /// Gets or sets a list of task exit code ranges and how the Batch service should respond to them. /// </summary> public IList<ExitCodeRangeMapping> ExitCodeRanges { get { return this.propertyContainer.ExitCodeRangesProperty.Value; } set { this.propertyContainer.ExitCodeRangesProperty.Value = ConcurrentChangeTrackedModifiableList<ExitCodeRangeMapping>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets a list of task exit codes and how the Batch service should respond to them. /// </summary> public IList<ExitCodeMapping> ExitCodes { get { return this.propertyContainer.ExitCodesProperty.Value; } set { this.propertyContainer.ExitCodesProperty.Value = ConcurrentChangeTrackedModifiableList<ExitCodeMapping>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets how the Batch service should respond if a file upload error occurs. /// </summary> /// <remarks> /// If the task exited with an exit code that was specified via <see cref="ExitCodes" /> or <see cref="ExitCodeRanges" /// />, and then encountered a file upload error, then the action specified by the exit code takes precedence. /// </remarks> public ExitOptions FileUploadError { get { return this.propertyContainer.FileUploadErrorProperty.Value; } set { this.propertyContainer.FileUploadErrorProperty.Value = value; } } /// <summary> /// Gets or sets how the Batch service should respond if the task fails to start due to an error. /// </summary> public ExitOptions PreProcessingError { get { return this.propertyContainer.PreProcessingErrorProperty.Value; } set { this.propertyContainer.PreProcessingErrorProperty.Value = value; } } #endregion // ExitConditions #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.ExitConditions ITransportObjectProvider<Models.ExitConditions>.GetTransportObject() { Models.ExitConditions result = new Models.ExitConditions() { DefaultProperty = UtilitiesInternal.CreateObjectWithNullCheck(this.Default, (o) => o.GetTransportObject()), ExitCodeRanges = UtilitiesInternal.ConvertToProtocolCollection(this.ExitCodeRanges), ExitCodes = UtilitiesInternal.ConvertToProtocolCollection(this.ExitCodes), FileUploadError = UtilitiesInternal.CreateObjectWithNullCheck(this.FileUploadError, (o) => o.GetTransportObject()), PreProcessingError = UtilitiesInternal.CreateObjectWithNullCheck(this.PreProcessingError, (o) => o.GetTransportObject()), }; return result; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects. /// </summary> internal static IList<ExitConditions> ConvertFromProtocolCollection(IEnumerable<Models.ExitConditions> protoCollection) { ConcurrentChangeTrackedModifiableList<ExitConditions> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable( items: protoCollection, objectCreationFunc: o => new ExitConditions(o)); return converted; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects, in a frozen state. /// </summary> internal static IList<ExitConditions> ConvertFromProtocolCollectionAndFreeze(IEnumerable<Models.ExitConditions> protoCollection) { ConcurrentChangeTrackedModifiableList<ExitConditions> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable( items: protoCollection, objectCreationFunc: o => new ExitConditions(o).Freeze()); converted = UtilitiesInternal.CreateObjectWithNullCheck(converted, o => o.Freeze()); return converted; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects, with each object marked readonly /// and returned as a readonly collection. /// </summary> internal static IReadOnlyList<ExitConditions> ConvertFromProtocolCollectionReadOnly(IEnumerable<Models.ExitConditions> protoCollection) { IReadOnlyList<ExitConditions> converted = UtilitiesInternal.CreateObjectWithNullCheck( UtilitiesInternal.CollectionToNonThreadSafeCollection( items: protoCollection, objectCreationFunc: o => new ExitConditions(o).Freeze()), o => o.AsReadOnly()); return converted; } #endregion // Internal/private methods } }
// 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.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public class CSharpCommandLineParser : CommandLineParser { public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser(); internal static CSharpCommandLineParser ScriptRunner { get; } = new CSharpCommandLineParser(isScriptRunner: true); internal CSharpCommandLineParser(bool isScriptRunner = false) : base(CSharp.MessageProvider.Instance, isScriptRunner) { } protected override string RegularFileExtension { get { return ".cs"; } } protected override string ScriptFileExtension { get { return ".csx"; } } internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories) { return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories); } /// <summary> /// Parses a command line. /// </summary> /// <param name="args">A collection of strings representing the command line arguments.</param> /// <param name="baseDirectory">The base directory used for qualifying file locations.</param> /// <param name="sdkDirectory">The directory to search for mscorlib, or null if not available.</param> /// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> /// <returns>a commandlinearguments object representing the parsed command line.</returns> public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null) { List<Diagnostic> diagnostics = new List<Diagnostic>(); List<string> flattenedArgs = new List<string>(); List<string> scriptArgs = IsScriptRunner ? new List<string>() : null; List<string> responsePaths = IsScriptRunner ? new List<string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory, responsePaths); string appConfigPath = null; bool displayLogo = true; bool displayHelp = false; bool displayVersion = false; bool optimize = false; bool checkOverflow = false; bool allowUnsafe = false; bool concurrentBuild = true; bool deterministic = false; // TODO(5431): Enable deterministic mode by default bool emitPdb = false; DebugInformationFormat debugInformationFormat = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; bool debugPlus = false; string pdbPath = null; bool noStdLib = IsScriptRunner; // don't add mscorlib from sdk dir when running scripts string outputDirectory = baseDirectory; ImmutableArray<KeyValuePair<string, string>> pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; string outputFileName = null; string documentationPath = null; string errorLogPath = null; bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid. bool utf8output = false; OutputKind outputKind = OutputKind.ConsoleApplication; SubsystemVersion subsystemVersion = SubsystemVersion.None; LanguageVersion languageVersion = LanguageVersion.Default; string mainTypeName = null; string win32ManifestFile = null; string win32ResourceFile = null; string win32IconFile = null; bool noWin32Manifest = false; Platform platform = Platform.AnyCpu; ulong baseAddress = 0; int fileAlignment = 0; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; List<ResourceDescription> managedResources = new List<ResourceDescription>(); List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> embeddedFiles = new List<CommandLineSourceFile>(); bool sourceFilesSpecified = false; bool embedAllSourceFiles = false; bool resourcesOrModulesSpecified = false; Encoding codepage = null; var checksumAlgorithm = SourceHashAlgorithm.Sha1; var defines = ArrayBuilder<string>.GetInstance(); List<CommandLineReference> metadataReferences = new List<CommandLineReference>(); List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>(); List<string> libPaths = new List<string>(); List<string> sourcePaths = new List<string>(); List<string> keyFileSearchPaths = new List<string>(); List<string> usings = new List<string>(); var generalDiagnosticOption = ReportDiagnostic.Default; var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(); var noWarns = new Dictionary<string, ReportDiagnostic>(); var warnAsErrors = new Dictionary<string, ReportDiagnostic>(); int warningLevel = 4; bool highEntropyVA = false; bool printFullPaths = false; string moduleAssemblyName = null; string moduleName = null; List<string> features = new List<string>(); string runtimeMetadataVersion = null; bool errorEndLocation = false; bool reportAnalyzer = false; ArrayBuilder<InstrumentationKind> instrumentationKinds = ArrayBuilder<InstrumentationKind>.GetInstance(); CultureInfo preferredUILang = null; string touchedFilesPath = null; bool optionsEnded = false; bool interactiveMode = false; bool publicSign = false; string sourceLink = null; // Process ruleset files first so that diagnostic severity settings specified on the command line via // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. if (!IsScriptRunner) { foreach (string arg in flattenedArgs) { string name, value; if (TryParseOption(arg, out name, out value) && (name == "ruleset")) { var unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory); } } } } foreach (string arg in flattenedArgs) { Debug.Assert(optionsEnded || !arg.StartsWith("@", StringComparison.Ordinal)); string name, value; if (optionsEnded || !TryParseOption(arg, out name, out value)) { sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics)); if (sourceFiles.Count > 0) { sourceFilesSpecified = true; } continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "version": displayVersion = true; continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "features": if (value == null) { features.Clear(); } else { features.Add(value); } continue; case "lib": case "libpath": case "libpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics); continue; #if DEBUG case "attachdebugger": Debugger.Launch(); continue; #endif } if (IsScriptRunner) { switch (name) { case "-": // csi -- script.csx if (value != null) break; // Indicates that the remaining arguments should not be treated as options. optionsEnded = true; continue; case "i": case "i+": if (value != null) break; interactiveMode = true; continue; case "i-": if (value != null) break; interactiveMode = false; continue; case "loadpath": case "loadpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, sourcePaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics); continue; case "u": case "using": case "usings": case "import": case "imports": usings.AddRange(ParseUsings(arg, value, diagnostics)); continue; } } else { switch (name) { case "a": case "analyzer": analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics)); continue; case "d": case "define": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } IEnumerable<Diagnostic> defineDiagnostics; defines.AddRange(ParseConditionalCompilationSymbols(RemoveQuotesAndSlashes(value), out defineDiagnostics)); diagnostics.AddRange(defineDiagnostics); continue; case "codepage": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var encoding = TryParseEncodingName(value); if (encoding == null) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value); continue; } codepage = encoding; continue; case "checksumalgorithm": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var newChecksumAlgorithm = TryParseHashAlgorithmName(value); if (newChecksumAlgorithm == SourceHashAlgorithm.None) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value); continue; } checksumAlgorithm = newChecksumAlgorithm; continue; case "checked": case "checked+": if (value != null) { break; } checkOverflow = true; continue; case "checked-": if (value != null) break; checkOverflow = false; continue; case "instrument": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { foreach (InstrumentationKind instrumentationKind in ParseInstrumentationKinds(value, diagnostics)) { if (!instrumentationKinds.Contains(instrumentationKind)) { instrumentationKinds.Add(instrumentationKind); } } } continue; case "noconfig": // It is already handled (see CommonCommandLineCompiler.cs). continue; case "sqmsessionguid": // The use of SQM is deprecated in the compiler but we still support the parsing of the option for // back compat reasons. if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name); } else { Guid sqmSessionGuid; if (!Guid.TryParse(value, out sqmSessionGuid)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name); } } continue; case "preferreduilang": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } try { preferredUILang = new CultureInfo(value); if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false) { // Do not use user custom cultures. preferredUILang = null; } } catch (CultureNotFoundException) { } if (preferredUILang == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value); } continue; case "out": if (string.IsNullOrWhiteSpace(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "moduleassemblyname": value = value != null ? value.Unquote() : null; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); } else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value)) { // Dev11 C# doesn't check the name (VB does) AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg); } else { moduleAssemblyName = value; } continue; case "modulename": var unquotedModuleName = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); continue; } else { moduleName = unquotedModuleName; } continue; case "platform": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg); } else { platform = ParsePlatform(value, diagnostics); } continue; case "recurse": value = RemoveQuotesAndSlashes(value); if (value == null) { break; // force 'unrecognized option' } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { int before = sourceFiles.Count; sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)); if (sourceFiles.Count > before) { sourceFilesSpecified = true; } } continue; case "doc": parseDocumentationComments = true; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); continue; } string unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out) // if we just let the next case handle /doc:"". AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument. } else { documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "addmodule": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. // An error will be reported by the assembly manager anyways. metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module))); resourcesOrModulesSpecified = true; } continue; case "l": case "link": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true)); continue; case "win32res": win32ResourceFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32icon": win32IconFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32manifest": win32ManifestFile = GetWin32Setting(arg, value, diagnostics); noWin32Manifest = false; continue; case "nowin32manifest": noWin32Manifest = true; win32ManifestFile = null; continue; case "res": case "resource": if (value == null) { break; // Dev11 reports unrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports unrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; case "sourcelink": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { sourceLink = ParseGenericPathToFile(value, diagnostics, baseDirectory); } continue; case "debug": emitPdb = true; // unused, parsed for backward compat only value = RemoveQuotesAndSlashes(value); if (value != null) { if (value.IsEmpty()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name); continue; } switch (value.ToLower()) { case "full": case "pdbonly": debugInformationFormat = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; break; case "portable": debugInformationFormat = DebugInformationFormat.PortablePdb; break; case "embedded": debugInformationFormat = DebugInformationFormat.Embedded; break; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); break; } } continue; case "debug+": //guard against "debug+:xx" if (value != null) break; emitPdb = true; debugPlus = true; continue; case "debug-": if (value != null) break; emitPdb = false; debugPlus = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) break; optimize = true; continue; case "o-": case "optimize-": if (value != null) break; optimize = false; continue; case "deterministic": case "deterministic+": if (value != null) break; deterministic = true; continue; case "deterministic-": if (value != null) break; deterministic = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) break; concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) break; concurrentBuild = false; continue; case "warnaserror": case "warnaserror+": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Error; // Reset specific warnaserror options (since last /warnaserror flag on the command line always wins), // and bump warnings to errors. warnAsErrors.Clear(); foreach (var key in diagnosticOptions.Keys) { if (diagnosticOptions[key] == ReportDiagnostic.Warn) { warnAsErrors[key] = ReportDiagnostic.Error; } } continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value)); } continue; case "warnaserror-": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Default; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { foreach (var id in ParseWarnings(value)) { ReportDiagnostic ruleSetValue; if (diagnosticOptions.TryGetValue(id, out ruleSetValue)) { warnAsErrors[id] = ruleSetValue; } else { warnAsErrors[id] = ReportDiagnostic.Default; } } } continue; case "w": case "warn": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } int newWarningLevel; if (string.IsNullOrEmpty(value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (newWarningLevel < 0 || newWarningLevel > 4) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name); } else { warningLevel = newWarningLevel; } continue; case "nowarn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value)); } continue; case "unsafe": case "unsafe+": if (value != null) break; allowUnsafe = true; continue; case "unsafe-": if (value != null) break; allowUnsafe = false; continue; case "langversion": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); } else if (!value.TryParse(out languageVersion)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "publicsign": case "publicsign+": if (value != null) { break; } publicSign = true; continue; case "publicsign-": if (value != null) { break; } publicSign = false; continue; case "keyfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = RemoveQuotesAndSlashes(value); } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "highentropyva": case "highentropyva+": if (value != null) break; highEntropyVA = true; continue; case "highentropyva-": if (value != null) break; highEntropyVA = false; continue; case "nologo": displayLogo = false; continue; case "baseaddress": value = RemoveQuotesAndSlashes(value); ulong newBaseAddress; if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress)) { if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value); } } else { baseAddress = newBaseAddress; } continue; case "subsystemversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); continue; } // It seems VS 2012 just silently corrects invalid values and suppresses the error message SubsystemVersion version = SubsystemVersion.None; if (SubsystemVersion.TryParse(value, out version)) { subsystemVersion = version; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value); } continue; case "touchedfiles": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); continue; } else { touchedFilesPath = unquoted; } continue; case "bugreport": UnimplementedSwitch(diagnostics, name); continue; case "utf8output": if (value != null) break; utf8output = true; continue; case "m": case "main": // Remove any quotes for consistent behavior as MSBuild can return quoted or // unquoted main. unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } mainTypeName = unquoted; continue; case "fullpaths": if (value != null) break; printFullPaths = true; continue; case "pathmap": // "/pathmap:K1=V1,K2=V2..." { if (value == null) break; pathMap = pathMap.Concat(ParsePathMap(value, diagnostics)); } continue; case "filealign": value = RemoveQuotesAndSlashes(value); ushort newAlignment; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (!TryParseUInt16(value, out newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else if (!CompilationOptions.IsValidFileAlignment(newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else { fileAlignment = newAlignment; } continue; case "pdb": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "errorendlocation": errorEndLocation = true; continue; case "reportanalyzer": reportAnalyzer = true; continue; case "nostdlib": case "nostdlib+": if (value != null) break; noStdLib = true; continue; case "nostdlib-": if (value != null) break; noStdLib = false; continue; case "errorreport": continue; case "errorlog": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveQuotesAndSlashes(arg)); } else { errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "appconfig": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveQuotesAndSlashes(arg)); } else { appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "runtimemetadataversion": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } runtimeMetadataVersion = unquoted; continue; case "ruleset": // The ruleset arg has already been processed in a separate pass above. continue; case "additionalfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name); continue; } additionalFiles.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)); continue; case "embed": if (string.IsNullOrEmpty(value)) { embedAllSourceFiles = true; continue; } embeddedFiles.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)); continue; } } AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg); } foreach (var o in warnAsErrors) { diagnosticOptions[o.Key] = o.Value; } // Specific nowarn options always override specific warnaserror options. foreach (var o in noWarns) { diagnosticOptions[o.Key] = o.Value; } if (!IsScriptRunner && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources); } if (!noStdLib && sdkDirectory != null) { metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly)); } if (!platform.Requires64Bit()) { if (baseAddress > uint.MaxValue - 0x8000) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress)); baseAddress = 0; } } // add additional reference paths if specified if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories)) { ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics); } ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths, responsePaths); ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics); // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } // Public sign doesn't use the legacy search path settings if (publicSign && !string.IsNullOrWhiteSpace(keyFileSetting)) { keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory); } if (sourceLink != null) { if (!emitPdb || !debugInformationFormat.IsPortable()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SourceLinkRequiresPortablePdb); } } if (embedAllSourceFiles) { embeddedFiles.AddRange(sourceFiles); } if (embeddedFiles.Count > 0) { // Restricted to portable PDBs for now, but the IsPortable condition should be removed // and the error message adjusted accordingly when native PDB support is added. if (!emitPdb || !debugInformationFormat.IsPortable()) { AddDiagnostic(diagnostics, ErrorCode.ERR_CannotEmbedWithoutPdb); } } var parsedFeatures = ParseFeatures(features); string compilationName; GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName); var parseOptions = new CSharpParseOptions ( languageVersion: languageVersion, preprocessorSymbols: defines.ToImmutableAndFree(), documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None, kind: IsScriptRunner ? SourceCodeKind.Script : SourceCodeKind.Regular, features: parsedFeatures ); // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics won't be reported on the command line. var reportSuppressedDiagnostics = errorLogPath != null; var options = new CSharpCompilationOptions ( outputKind: outputKind, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: checkOverflow, allowUnsafe: allowUnsafe, deterministic: deterministic, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: platform, generalDiagnosticOption: generalDiagnosticOption, warningLevel: warningLevel, specificDiagnosticOptions: diagnosticOptions, reportSuppressedDiagnostics: reportSuppressedDiagnostics, publicSign: publicSign ); if (debugPlus) { options = options.WithDebugPlusMode(debugPlus); } var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: debugInformationFormat, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later baseAddress: baseAddress, highEntropyVirtualAddressSpace: highEntropyVA, fileAlignment: fileAlignment, subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion, instrumentationKinds: instrumentationKinds.ToImmutableAndFree() ); // add option incompatibility errors if any diagnostics.AddRange(options.Errors); diagnostics.AddRange(parseOptions.Errors); return new CSharpCommandLineArguments { IsScriptRunner = IsScriptRunner, InteractiveMode = interactiveMode || IsScriptRunner && sourceFiles.Count == 0, BaseDirectory = baseDirectory, PathMap = pathMap, Errors = diagnostics.AsImmutable(), Utf8Output = utf8output, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, SourceLink = sourceLink, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, ErrorLogPath = errorLogPath, AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = codepage, ChecksumAlgorithm = checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths, SourcePaths = sourcePaths.AsImmutable(), KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), Win32ResourceFile = win32ResourceFile, Win32Icon = win32IconFile, Win32Manifest = win32ManifestFile, NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, DisplayVersion = displayVersion, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = parseOptions, EmitOptions = emitOptions, ScriptArguments = scriptArgs.AsImmutableOrEmpty(), TouchedFilesPath = touchedFilesPath, PrintFullPaths = printFullPaths, ShouldIncludeErrorEndLocation = errorEndLocation, PreferredUILang = preferredUILang, ReportAnalyzer = reportAnalyzer, EmbeddedFiles = embeddedFiles.AsImmutable() }; } private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics) { if (string.IsNullOrEmpty(switchValue)) { Debug.Assert(!string.IsNullOrEmpty(switchName)); AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); return; } foreach (string path in ParseSeparatedPaths(switchValue)) { string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (resolvedPath == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); } else if (!Directory.Exists(resolvedPath)) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); } else { builder.Add(resolvedPath); } } } private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { string noQuotes = RemoveQuotesAndSlashes(value); if (string.IsNullOrWhiteSpace(noQuotes)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { return noQuotes; } } return null; } private void GetCompilationAndModuleNames( List<Diagnostic> diagnostics, OutputKind outputKind, List<CommandLineSourceFile> sourceFiles, bool sourceFilesSpecified, string moduleAssemblyName, ref string outputFileName, ref string moduleName, out string compilationName) { string simpleName; if (outputFileName == null) { // In C#, if the output file name isn't specified explicitly, then executables take their // names from the files containing their entrypoints and libraries derive their names from // their first input files. if (!IsScriptRunner && !sourceFilesSpecified) { AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); simpleName = null; } else if (outputKind.IsApplication()) { simpleName = null; } else { simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path)); outputFileName = simpleName + outputKind.GetDefaultExtension(); if (simpleName.Length == 0 && !outputKind.IsNetModule()) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } } else { simpleName = PathUtilities.RemoveExtension(outputFileName); if (simpleName.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } if (outputKind.IsNetModule()) { Debug.Assert(!IsScriptRunner); compilationName = moduleAssemblyName; } else { if (moduleAssemblyName != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); } compilationName = simpleName; } if (moduleName == null) { moduleName = outputFileName; } } private ImmutableArray<string> BuildSearchPaths(string sdkDirectoryOpt, List<string> libPaths, List<string> responsePathsOpt) { var builder = ArrayBuilder<string>.GetInstance(); // Match how Dev11 builds the list of search paths // see PCWSTR LangCompiler::GetSearchPath() // current folder first -- base directory is searched by default // Add SDK directory if it is available if (sdkDirectoryOpt != null) { builder.Add(sdkDirectoryOpt); } // libpath builder.AddRange(libPaths); // csi adds paths of the response file(s) to the search paths, so that we can initialize the script environment // with references relative to csi.exe (e.g. System.ValueTuple.dll). if (responsePathsOpt != null) { Debug.Assert(IsScriptRunner); builder.AddRange(responsePathsOpt); } return builder.ToImmutableAndFree(); } public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics) { DiagnosticBag outputDiagnostics = DiagnosticBag.GetInstance(); value = value.TrimEnd(null); // Allow a trailing semicolon or comma in the options if (!value.IsEmpty() && (value.Last() == ';' || value.Last() == ',')) { value = value.Substring(0, value.Length - 1); } string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/); var defines = new ArrayBuilder<string>(values.Length); foreach (string id in values) { string trimmedId = id.Trim(); if (SyntaxFacts.IsValidIdentifier(trimmedId)) { defines.Add(trimmedId); } else { outputDiagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId)); } } diagnostics = outputDiagnostics.ToReadOnlyAndFree(); return defines.AsEnumerable(); } private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "x86": return Platform.X86; case "x64": return Platform.X64; case "itanium": return Platform.Itanium; case "anycpu": return Platform.AnyCpu; case "anycpu32bitpreferred": return Platform.AnyCpu32BitPreferred; case "arm": return Platform.Arm; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); return Platform.AnyCpu; } } private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "exe": return OutputKind.ConsoleApplication; case "winexe": return OutputKind.WindowsApplication; case "library": return OutputKind.DynamicallyLinkedLibrary; case "module": return OutputKind.NetModule; case "appcontainerexe": return OutputKind.WindowsRuntimeApplication; case "winmdobj": return OutputKind.WindowsRuntimeMetadata; default: AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); return OutputKind.ConsoleApplication; } } private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics) { if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); yield break; } foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { yield return u; } } private static IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); foreach (string path in paths) { yield return new CommandLineAnalyzerReference(path); } } private static IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } // /r:"reference" // /r:alias=reference // /r:alias="reference" // /r:reference;reference // /r:"path;containing;semicolons" // /r:"unterminated_quotes // /r:"quotes"in"the"middle // /r:alias=reference;reference ... error 2034 // /r:nonidf=reference ... error 1679 int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' }); string alias; if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=') { alias = value.Substring(0, eqlOrQuote); value = value.Substring(eqlOrQuote + 1); if (!SyntaxFacts.IsValidIdentifier(alias)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias); yield break; } } else { alias = null; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); if (alias != null) { if (paths.Count > 1) { AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value); yield break; } if (paths.Count == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias); yield break; } } foreach (string path in paths) { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty; var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); yield return new CommandLineReference(path, properties); } } private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics) { if (win32ResourceFile != null) { if (win32IconResourceFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); } if (win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); } } if (outputKind.IsNetModule() && win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); } } private static IEnumerable<InstrumentationKind> ParseInstrumentationKinds(string value, IList<Diagnostic> diagnostics) { string[] kinds = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var kind in kinds) { switch (kind.ToLower()) { case "testcoverage": yield return InstrumentationKind.TestCoverage; break; default: AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidInstrumentationKind, kind); break; } } } internal static ResourceDescription ParseResourceDescription( string arg, string resourceDescriptor, string baseDirectory, IList<Diagnostic> diagnostics, bool embedded) { string filePath; string fullPath; string fileName; string resourceName; string accessibility; ParseResourceDescription( resourceDescriptor, baseDirectory, false, out filePath, out fullPath, out fileName, out resourceName, out accessibility); bool isPublic; if (accessibility == null) { // If no accessibility is given, we default to "public". // NOTE: Dev10 distinguishes between null and empty/whitespace-only. isPublic = true; } else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase)) { isPublic = true; } else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase)) { isPublic = false; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility); return null; } if (string.IsNullOrEmpty(filePath)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); return null; } if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath); return null; } Func<Stream> dataProvider = () => { // Use FileShare.ReadWrite because the file could be opened by the current process. // For example, it is an XML doc file produced by the build. return new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); }; return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false); } private static IEnumerable<string> ParseWarnings(string value) { value = value.Unquote(); string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { ushort number; if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) && ErrorFacts.IsWarning((ErrorCode)number)) { // The id refers to a compiler warning. yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number); } else { // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in /nowarn or // /warnaserror. We no longer generate a warning in such cases. // Instead we assume that the unrecognized id refers to a custom diagnostic. yield return id; } } } private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items) { foreach (var id in items) { ReportDiagnostic existing; if (d.TryGetValue(id, out existing)) { // Rewrite the existing value with the latest one unless it is for /nowarn. if (existing != ReportDiagnostic.Suppress) d[id] = kind; } else { d.Add(id, kind); } } } private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); } internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics) { // no error in csc.exe } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode)); } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments)); } /// <summary> /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode. /// </summary> private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments) { int code = (int)errorCode; ReportDiagnostic value; warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value); if (value != ReportDiagnostic.Suppress) { AddDiagnostic(diagnostics, errorCode, arguments); } } } }
//------------------------------------------------------------------------------ // <copyright file="EnumRowCollectionExtensions.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Globalization; using System.Diagnostics; namespace System.Data { /// <summary> /// This static class defines the extension methods that add LINQ operator functionality /// within IEnumerableDT and IOrderedEnumerableDT. /// </summary> public static class EnumerableRowCollectionExtensions { /// <summary> /// LINQ's Where operator for generic EnumerableRowCollection. /// </summary> public static EnumerableRowCollection<TRow> Where<TRow>( this EnumerableRowCollection<TRow> source, Func<TRow, bool> predicate) { EnumerableRowCollection<TRow> edt = new EnumerableRowCollection<TRow>(source, Enumerable.Where<TRow>(source, predicate), null); //copy constructor edt.AddPredicate(predicate); return edt; } /// <summary> /// LINQ's OrderBy operator for generic EnumerableRowCollection. /// </summary> public static OrderedEnumerableRowCollection<TRow> OrderBy<TRow, TKey>( this EnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector) { IEnumerable<TRow> ie = Enumerable.OrderBy<TRow, TKey>(source, keySelector); OrderedEnumerableRowCollection<TRow> edt = new OrderedEnumerableRowCollection<TRow>(source, ie); edt.AddSortExpression(keySelector, false, true); return edt; } /// <summary> /// LINQ's OrderBy operator for generic EnumerableRowCollection. /// </summary> public static OrderedEnumerableRowCollection<TRow> OrderBy<TRow, TKey>( this EnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector, IComparer<TKey> comparer) { IEnumerable<TRow> ie = Enumerable.OrderBy<TRow, TKey>(source, keySelector, comparer); OrderedEnumerableRowCollection<TRow> edt = new OrderedEnumerableRowCollection<TRow>(source, ie); edt.AddSortExpression(keySelector, comparer, false, true); return edt; } /// <summary> /// LINQ's OrderByDescending operator for generic EnumerableRowCollection. /// </summary> public static OrderedEnumerableRowCollection<TRow> OrderByDescending<TRow, TKey>( this EnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector) { IEnumerable<TRow> ie = Enumerable.OrderByDescending<TRow, TKey>(source, keySelector); OrderedEnumerableRowCollection<TRow> edt = new OrderedEnumerableRowCollection<TRow>(source, ie); edt.AddSortExpression(keySelector, true, true); return edt; } /// <summary> /// LINQ's OrderByDescending operator for generic EnumerableRowCollection. /// </summary> public static OrderedEnumerableRowCollection<TRow> OrderByDescending<TRow, TKey>( this EnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector, IComparer<TKey> comparer) { IEnumerable<TRow> ie = Enumerable.OrderByDescending<TRow, TKey>(source, keySelector, comparer); OrderedEnumerableRowCollection<TRow> edt = new OrderedEnumerableRowCollection<TRow>(source, ie); edt.AddSortExpression(keySelector, comparer, true, true); return edt; } /// <summary> /// LINQ's ThenBy operator for generic EnumerableRowCollection. /// </summary> public static OrderedEnumerableRowCollection<TRow> ThenBy<TRow, TKey>( this OrderedEnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector) { IEnumerable<TRow> ie = Enumerable.ThenBy<TRow, TKey>((IOrderedEnumerable<TRow>)source.EnumerableRows, keySelector); OrderedEnumerableRowCollection<TRow> edt = new OrderedEnumerableRowCollection<TRow>((EnumerableRowCollection<TRow>)source, ie); edt.AddSortExpression(keySelector, /*isDesc*/ false, /*isOrderBy*/ false); return edt; } /// <summary> /// LINQ's ThenBy operator for generic EnumerableRowCollection. /// </summary> public static OrderedEnumerableRowCollection<TRow> ThenBy<TRow, TKey>( this OrderedEnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector, IComparer<TKey> comparer) { IEnumerable<TRow> ie = Enumerable.ThenBy<TRow, TKey>((IOrderedEnumerable<TRow>)source.EnumerableRows, keySelector, comparer); OrderedEnumerableRowCollection<TRow> edt = new OrderedEnumerableRowCollection<TRow>((EnumerableRowCollection<TRow>)source, ie); edt.AddSortExpression(keySelector, comparer, false, false); return edt; } /// <summary> /// LINQ's ThenByDescending operator for generic EnumerableRowCollection. /// </summary> public static OrderedEnumerableRowCollection<TRow> ThenByDescending<TRow, TKey>( this OrderedEnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector) { IEnumerable<TRow> ie = Enumerable.ThenByDescending<TRow, TKey>((IOrderedEnumerable<TRow>)source.EnumerableRows, keySelector); OrderedEnumerableRowCollection<TRow> edt = new OrderedEnumerableRowCollection<TRow>((EnumerableRowCollection<TRow>)source, ie); edt.AddSortExpression(keySelector, /*desc*/ true, false); return edt; } /// <summary> /// LINQ's ThenByDescending operator for generic EnumerableRowCollection. /// </summary> public static OrderedEnumerableRowCollection<TRow> ThenByDescending<TRow, TKey>( this OrderedEnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector, IComparer<TKey> comparer) { IEnumerable<TRow> ie = Enumerable.ThenByDescending<TRow, TKey>((IOrderedEnumerable<TRow>)source.EnumerableRows, keySelector, comparer); OrderedEnumerableRowCollection<TRow> edt = new OrderedEnumerableRowCollection<TRow>((EnumerableRowCollection<TRow>)source, ie); edt.AddSortExpression(keySelector, comparer, true, false); return edt; } /// <summary> /// Executes a Select (Projection) on EnumerableDataTable. If the selector returns a different /// type than the type of rows, then AsLinqDataView is disabled, and the returning EnumerableDataTable /// represents an enumerable over the LINQ Query. /// </summary> public static EnumerableRowCollection<S> Select<TRow, S>( this EnumerableRowCollection<TRow> source, Func<TRow, S> selector) { //Anonymous type or some other type //The only thing that matters from this point on is _enumerableRows IEnumerable<S> typedEnumerable = Enumerable.Select<TRow, S>(source, selector); // Dont need predicates or sort expression from this point on since we know // AsLinqDataView is disabled. return new EnumerableRowCollection<S>(((object)source) as EnumerableRowCollection<S>, typedEnumerable, ((object)selector) as Func<S,S>); } /// <summary> /// Casts an EnumerableDataTable_TSource into EnumerableDataTable_TResult /// </summary> public static EnumerableRowCollection<TResult> Cast<TResult>(this EnumerableRowCollection source) { // Since Cast does not have the signature Cast_T_R(..) this call is routed // through the non-generic base class EnumerableDataTable if ((null != source) && source.ElementType.Equals(typeof(TResult))) { return (EnumerableRowCollection<TResult>)(object)source; } else { //Anonymous type or some other type //The only thing that matters from this point on is _enumerableRows IEnumerable<TResult> typedEnumerable = Enumerable.Cast<TResult>(source); EnumerableRowCollection<TResult> newEdt = new EnumerableRowCollection<TResult>( typedEnumerable, typeof(TResult).IsAssignableFrom(source.ElementType) && typeof(DataRow).IsAssignableFrom(typeof(TResult)), source.Table); return newEdt; } } } //end class }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Binary.Metadata; using Apache.Ignite.Core.Impl.Binary.Structure; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Binary writer implementation. /// </summary> internal class BinaryWriter : IBinaryWriter, IBinaryRawWriter { /** Marshaller. */ private readonly Marshaller _marsh; /** Stream. */ private readonly IBinaryStream _stream; /** Builder (used only during build). */ private BinaryObjectBuilder _builder; /** Handles. */ private BinaryHandleDictionary<object, long> _hnds; /** Metadatas collected during this write session. */ private IDictionary<int, BinaryType> _metas; /** Current stack frame. */ private Frame _frame; /** Whether we are currently detaching an object. */ private bool _detaching; /** Whether we are directly within peer loading object holder. */ private bool _isInWrapper; /** Schema holder. */ private readonly BinaryObjectSchemaHolder _schema = BinaryObjectSchemaHolder.Current; /// <summary> /// Gets the marshaller. /// </summary> internal Marshaller Marshaller { get { return _marsh; } } /// <summary> /// Invoked when binary object writing finishes. /// </summary> internal event Action<BinaryObjectHeader, object> OnObjectWritten; /// <summary> /// Write named boolean value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Boolean value.</param> public void WriteBoolean(string fieldName, bool val) { WriteFieldId(fieldName, BinaryTypeId.Bool); WriteBooleanField(val); } /// <summary> /// Writes the boolean field. /// </summary> /// <param name="val">if set to <c>true</c> [value].</param> internal void WriteBooleanField(bool val) { _stream.WriteByte(BinaryTypeId.Bool); _stream.WriteBool(val); } /// <summary> /// Write boolean value. /// </summary> /// <param name="val">Boolean value.</param> public void WriteBoolean(bool val) { _stream.WriteBool(val); } /// <summary> /// Write named boolean array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Boolean array.</param> public void WriteBooleanArray(string fieldName, bool[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayBool); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayBool); BinaryUtils.WriteBooleanArray(val, _stream); } } /// <summary> /// Write boolean array. /// </summary> /// <param name="val">Boolean array.</param> public void WriteBooleanArray(bool[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayBool); BinaryUtils.WriteBooleanArray(val, _stream); } } /// <summary> /// Write named byte value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Byte value.</param> public void WriteByte(string fieldName, byte val) { WriteFieldId(fieldName, BinaryTypeId.Byte); WriteByteField(val); } /// <summary> /// Write byte field value. /// </summary> /// <param name="val">Byte value.</param> internal void WriteByteField(byte val) { _stream.WriteByte(BinaryTypeId.Byte); _stream.WriteByte(val); } /// <summary> /// Write byte value. /// </summary> /// <param name="val">Byte value.</param> public void WriteByte(byte val) { _stream.WriteByte(val); } /// <summary> /// Write named byte array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Byte array.</param> public void WriteByteArray(string fieldName, byte[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayByte); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayByte); BinaryUtils.WriteByteArray(val, _stream); } } /// <summary> /// Write byte array. /// </summary> /// <param name="val">Byte array.</param> public void WriteByteArray(byte[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayByte); BinaryUtils.WriteByteArray(val, _stream); } } /// <summary> /// Write named short value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Short value.</param> public void WriteShort(string fieldName, short val) { WriteFieldId(fieldName, BinaryTypeId.Short); WriteShortField(val); } /// <summary> /// Write short field value. /// </summary> /// <param name="val">Short value.</param> internal void WriteShortField(short val) { _stream.WriteByte(BinaryTypeId.Short); _stream.WriteShort(val); } /// <summary> /// Write short value. /// </summary> /// <param name="val">Short value.</param> public void WriteShort(short val) { _stream.WriteShort(val); } /// <summary> /// Write named short array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Short array.</param> public void WriteShortArray(string fieldName, short[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayShort); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayShort); BinaryUtils.WriteShortArray(val, _stream); } } /// <summary> /// Write short array. /// </summary> /// <param name="val">Short array.</param> public void WriteShortArray(short[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayShort); BinaryUtils.WriteShortArray(val, _stream); } } /// <summary> /// Write named char value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Char value.</param> public void WriteChar(string fieldName, char val) { WriteFieldId(fieldName, BinaryTypeId.Char); WriteCharField(val); } /// <summary> /// Write char field value. /// </summary> /// <param name="val">Char value.</param> internal void WriteCharField(char val) { _stream.WriteByte(BinaryTypeId.Char); _stream.WriteChar(val); } /// <summary> /// Write char value. /// </summary> /// <param name="val">Char value.</param> public void WriteChar(char val) { _stream.WriteChar(val); } /// <summary> /// Write named char array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Char array.</param> public void WriteCharArray(string fieldName, char[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayChar); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayChar); BinaryUtils.WriteCharArray(val, _stream); } } /// <summary> /// Write char array. /// </summary> /// <param name="val">Char array.</param> public void WriteCharArray(char[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayChar); BinaryUtils.WriteCharArray(val, _stream); } } /// <summary> /// Write named int value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Int value.</param> public void WriteInt(string fieldName, int val) { WriteFieldId(fieldName, BinaryTypeId.Int); WriteIntField(val); } /// <summary> /// Writes the int field. /// </summary> /// <param name="val">The value.</param> internal void WriteIntField(int val) { _stream.WriteByte(BinaryTypeId.Int); _stream.WriteInt(val); } /// <summary> /// Write int value. /// </summary> /// <param name="val">Int value.</param> public void WriteInt(int val) { _stream.WriteInt(val); } /// <summary> /// Write named int array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Int array.</param> public void WriteIntArray(string fieldName, int[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayInt); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayInt); BinaryUtils.WriteIntArray(val, _stream); } } /// <summary> /// Write int array. /// </summary> /// <param name="val">Int array.</param> public void WriteIntArray(int[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayInt); BinaryUtils.WriteIntArray(val, _stream); } } /// <summary> /// Write named long value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Long value.</param> public void WriteLong(string fieldName, long val) { WriteFieldId(fieldName, BinaryTypeId.Long); WriteLongField(val); } /// <summary> /// Writes the long field. /// </summary> /// <param name="val">The value.</param> internal void WriteLongField(long val) { _stream.WriteByte(BinaryTypeId.Long); _stream.WriteLong(val); } /// <summary> /// Write long value. /// </summary> /// <param name="val">Long value.</param> public void WriteLong(long val) { _stream.WriteLong(val); } /// <summary> /// Write named long array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Long array.</param> public void WriteLongArray(string fieldName, long[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayLong); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayLong); BinaryUtils.WriteLongArray(val, _stream); } } /// <summary> /// Write long array. /// </summary> /// <param name="val">Long array.</param> public void WriteLongArray(long[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayLong); BinaryUtils.WriteLongArray(val, _stream); } } /// <summary> /// Write named float value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Float value.</param> public void WriteFloat(string fieldName, float val) { WriteFieldId(fieldName, BinaryTypeId.Float); WriteFloatField(val); } /// <summary> /// Writes the float field. /// </summary> /// <param name="val">The value.</param> internal void WriteFloatField(float val) { _stream.WriteByte(BinaryTypeId.Float); _stream.WriteFloat(val); } /// <summary> /// Write float value. /// </summary> /// <param name="val">Float value.</param> public void WriteFloat(float val) { _stream.WriteFloat(val); } /// <summary> /// Write named float array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Float array.</param> public void WriteFloatArray(string fieldName, float[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayFloat); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayFloat); BinaryUtils.WriteFloatArray(val, _stream); } } /// <summary> /// Write float array. /// </summary> /// <param name="val">Float array.</param> public void WriteFloatArray(float[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayFloat); BinaryUtils.WriteFloatArray(val, _stream); } } /// <summary> /// Write named double value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Double value.</param> public void WriteDouble(string fieldName, double val) { WriteFieldId(fieldName, BinaryTypeId.Double); WriteDoubleField(val); } /// <summary> /// Writes the double field. /// </summary> /// <param name="val">The value.</param> internal void WriteDoubleField(double val) { _stream.WriteByte(BinaryTypeId.Double); _stream.WriteDouble(val); } /// <summary> /// Write double value. /// </summary> /// <param name="val">Double value.</param> public void WriteDouble(double val) { _stream.WriteDouble(val); } /// <summary> /// Write named double array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Double array.</param> public void WriteDoubleArray(string fieldName, double[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayDouble); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayDouble); BinaryUtils.WriteDoubleArray(val, _stream); } } /// <summary> /// Write double array. /// </summary> /// <param name="val">Double array.</param> public void WriteDoubleArray(double[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayDouble); BinaryUtils.WriteDoubleArray(val, _stream); } } /// <summary> /// Write named decimal value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Decimal value.</param> public void WriteDecimal(string fieldName, decimal? val) { WriteFieldId(fieldName, BinaryTypeId.Decimal); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.Decimal); BinaryUtils.WriteDecimal(val.Value, _stream); } } /// <summary> /// Write decimal value. /// </summary> /// <param name="val">Decimal value.</param> public void WriteDecimal(decimal? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.Decimal); BinaryUtils.WriteDecimal(val.Value, _stream); } } /// <summary> /// Write named decimal array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Decimal array.</param> public void WriteDecimalArray(string fieldName, decimal?[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayDecimal); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayDecimal); BinaryUtils.WriteDecimalArray(val, _stream); } } /// <summary> /// Write decimal array. /// </summary> /// <param name="val">Decimal array.</param> public void WriteDecimalArray(decimal?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayDecimal); BinaryUtils.WriteDecimalArray(val, _stream); } } /// <summary> /// Write named date value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Date value.</param> public void WriteTimestamp(string fieldName, DateTime? val) { WriteFieldId(fieldName, BinaryTypeId.Timestamp); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.Timestamp); BinaryUtils.WriteTimestamp(val.Value, _stream); } } /// <summary> /// Write date value. /// </summary> /// <param name="val">Date value.</param> public void WriteTimestamp(DateTime? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.Timestamp); BinaryUtils.WriteTimestamp(val.Value, _stream); } } /// <summary> /// Write named date array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Date array.</param> public void WriteTimestampArray(string fieldName, DateTime?[] val) { WriteFieldId(fieldName, BinaryTypeId.Timestamp); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayTimestamp); BinaryUtils.WriteTimestampArray(val, _stream); } } /// <summary> /// Write date array. /// </summary> /// <param name="val">Date array.</param> public void WriteTimestampArray(DateTime?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayTimestamp); BinaryUtils.WriteTimestampArray(val, _stream); } } /// <summary> /// Write named string value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">String value.</param> public void WriteString(string fieldName, string val) { WriteFieldId(fieldName, BinaryTypeId.String); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.String); BinaryUtils.WriteString(val, _stream); } } /// <summary> /// Write string value. /// </summary> /// <param name="val">String value.</param> public void WriteString(string val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.String); BinaryUtils.WriteString(val, _stream); } } /// <summary> /// Write named string array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">String array.</param> public void WriteStringArray(string fieldName, string[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayString); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayString); BinaryUtils.WriteStringArray(val, _stream); } } /// <summary> /// Write string array. /// </summary> /// <param name="val">String array.</param> public void WriteStringArray(string[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayString); BinaryUtils.WriteStringArray(val, _stream); } } /// <summary> /// Write named GUID value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">GUID value.</param> public void WriteGuid(string fieldName, Guid? val) { WriteFieldId(fieldName, BinaryTypeId.Guid); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.Guid); BinaryUtils.WriteGuid(val.Value, _stream); } } /// <summary> /// Write GUID value. /// </summary> /// <param name="val">GUID value.</param> public void WriteGuid(Guid? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.Guid); BinaryUtils.WriteGuid(val.Value, _stream); } } /// <summary> /// Write named GUID array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">GUID array.</param> public void WriteGuidArray(string fieldName, Guid?[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayGuid); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayGuid); BinaryUtils.WriteGuidArray(val, _stream); } } /// <summary> /// Write GUID array. /// </summary> /// <param name="val">GUID array.</param> public void WriteGuidArray(Guid?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayGuid); BinaryUtils.WriteGuidArray(val, _stream); } } /// <summary> /// Write named enum value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Enum value.</param> public void WriteEnum<T>(string fieldName, T val) { WriteFieldId(fieldName, BinaryTypeId.Enum); WriteEnum(val); } /// <summary> /// Write enum value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Enum value.</param> public void WriteEnum<T>(T val) { // ReSharper disable once CompareNonConstrainedGenericWithNull if (val == null) WriteNullField(); else { // Unwrap nullable. var valType = val.GetType(); var type = Nullable.GetUnderlyingType(valType) ?? valType; if (!type.IsEnum) { throw new BinaryObjectException("Type is not an enum: " + type); } var handler = BinarySystemHandlers.GetWriteHandler(type); if (handler != null) { // All enums except long/ulong. handler.Write(this, val); } else { throw new BinaryObjectException(string.Format("Enum '{0}' has unsupported underlying type '{1}'. " + "Use WriteObject instead of WriteEnum.", type, Enum.GetUnderlyingType(type))); } } } /// <summary> /// Write enum value. /// </summary> /// <param name="val">Enum value.</param> /// <param name="type">Enum type.</param> internal void WriteEnum(int val, Type type) { var desc = _marsh.GetDescriptor(type); _stream.WriteByte(BinaryTypeId.Enum); _stream.WriteInt(desc.TypeId); _stream.WriteInt(val); var metaHnd = _marsh.GetBinaryTypeHandler(desc); SaveMetadata(desc, metaHnd.OnObjectWriteFinished()); } /// <summary> /// Write named enum array. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Enum array.</param> public void WriteEnumArray<T>(string fieldName, T[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayEnum); WriteEnumArray(val); } /// <summary> /// Write enum array. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Enum array.</param> public void WriteEnumArray<T>(T[] val) { WriteEnumArrayInternal(val, null); } /// <summary> /// Writes the enum array. /// </summary> /// <param name="val">The value.</param> /// <param name="elementTypeId">The element type id.</param> public void WriteEnumArrayInternal(Array val, int? elementTypeId) { if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayEnum); BinaryUtils.WriteArray(val, this, elementTypeId); } } /// <summary> /// Write named object value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Object value.</param> public void WriteObject<T>(string fieldName, T val) { WriteFieldId(fieldName, BinaryTypeId.Object); // ReSharper disable once CompareNonConstrainedGenericWithNull if (val == null) WriteNullField(); else Write(val); } /// <summary> /// Write object value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Object value.</param> public void WriteObject<T>(T val) { Write(val); } /// <summary> /// Write named object array. /// </summary> /// <typeparam name="T">Element type.</typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Object array.</param> public void WriteArray<T>(string fieldName, T[] val) { WriteFieldId(fieldName, BinaryTypeId.Array); WriteArray(val); } /// <summary> /// Write object array. /// </summary> /// <typeparam name="T">Element type.</typeparam> /// <param name="val">Object array.</param> public void WriteArray<T>(T[] val) { WriteArrayInternal(val); } /// <summary> /// Write object array. /// </summary> /// <param name="val">Object array.</param> public void WriteArrayInternal(Array val) { if (val == null) WriteNullRawField(); else { if (WriteHandle(_stream.Position, val)) return; _stream.WriteByte(BinaryTypeId.Array); BinaryUtils.WriteArray(val, this); } } /// <summary> /// Write named collection. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Collection.</param> public void WriteCollection(string fieldName, ICollection val) { WriteFieldId(fieldName, BinaryTypeId.Collection); WriteCollection(val); } /// <summary> /// Write collection. /// </summary> /// <param name="val">Collection.</param> public void WriteCollection(ICollection val) { if (val == null) WriteNullField(); else { if (WriteHandle(_stream.Position, val)) return; WriteByte(BinaryTypeId.Collection); BinaryUtils.WriteCollection(val, this); } } /// <summary> /// Write named dictionary. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Dictionary.</param> public void WriteDictionary(string fieldName, IDictionary val) { WriteFieldId(fieldName, BinaryTypeId.Dictionary); WriteDictionary(val); } /// <summary> /// Write dictionary. /// </summary> /// <param name="val">Dictionary.</param> public void WriteDictionary(IDictionary val) { if (val == null) WriteNullField(); else { if (WriteHandle(_stream.Position, val)) return; WriteByte(BinaryTypeId.Dictionary); BinaryUtils.WriteDictionary(val, this); } } /// <summary> /// Write NULL field. /// </summary> private void WriteNullField() { _stream.WriteByte(BinaryUtils.HdrNull); } /// <summary> /// Write NULL raw field. /// </summary> private void WriteNullRawField() { _stream.WriteByte(BinaryUtils.HdrNull); } /// <summary> /// Get raw writer. /// </summary> /// <returns> /// Raw writer. /// </returns> public IBinaryRawWriter GetRawWriter() { if (_frame.RawPos == 0) _frame.RawPos = _stream.Position; return this; } /// <summary> /// Set new builder. /// </summary> /// <param name="builder">Builder.</param> /// <returns>Previous builder.</returns> internal BinaryObjectBuilder SetBuilder(BinaryObjectBuilder builder) { BinaryObjectBuilder ret = _builder; _builder = builder; return ret; } /// <summary> /// Constructor. /// </summary> /// <param name="marsh">Marshaller.</param> /// <param name="stream">Stream.</param> internal BinaryWriter(Marshaller marsh, IBinaryStream stream) { _marsh = marsh; _stream = stream; } /// <summary> /// Write object. /// </summary> /// <param name="obj">Object.</param> public void Write<T>(T obj) { // Handle special case for null. // ReSharper disable once CompareNonConstrainedGenericWithNull if (obj == null) { _stream.WriteByte(BinaryUtils.HdrNull); return; } // We use GetType() of a real object instead of typeof(T) to take advantage of // automatic Nullable'1 unwrapping. Type type = obj.GetType(); // Handle common case when primitive is written. if (type.IsPrimitive) { WritePrimitive(obj, type); return; } // Handle special case for builder. if (WriteBuilderSpecials(obj)) return; // Are we dealing with a well-known type? var handler = BinarySystemHandlers.GetWriteHandler(type); if (handler != null) { if (handler.SupportsHandles && WriteHandle(_stream.Position, obj)) return; handler.Write(this, obj); return; } // Wrap objects as required. if (WrapperFunc != null && type != WrapperFunc.Method.ReturnType) { if (_isInWrapper) { _isInWrapper = false; } else { _isInWrapper = true; Write(WrapperFunc(obj)); return; } } // Suppose that we faced normal object and perform descriptor lookup. var desc = _marsh.GetDescriptor(type); // Writing normal object. var pos = _stream.Position; // Dealing with handles. if (desc.Serializer.SupportsHandles && WriteHandle(pos, obj)) return; // Skip header length as not everything is known now _stream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current); // Write type name for unregistered types if (!desc.IsRegistered) { WriteString(Marshaller.GetTypeName(type)); } var headerSize = _stream.Position - pos; // Preserve old frame. var oldFrame = _frame; // Push new frame. _frame.RawPos = 0; _frame.Pos = pos; _frame.Struct = new BinaryStructureTracker(desc, desc.WriterTypeStructure); _frame.HasCustomTypeData = false; var schemaIdx = _schema.PushSchema(); try { // Write object fields. desc.Serializer.WriteBinary(obj, this); var dataEnd = _stream.Position; // Write schema var schemaOffset = dataEnd - pos; int schemaId; var flags = desc.UserType ? BinaryObjectHeader.Flag.UserType : BinaryObjectHeader.Flag.None; if (_frame.HasCustomTypeData) flags |= BinaryObjectHeader.Flag.CustomDotNetType; if (Marshaller.CompactFooter && desc.UserType) flags |= BinaryObjectHeader.Flag.CompactFooter; var hasSchema = _schema.WriteSchema(_stream, schemaIdx, out schemaId, ref flags); if (hasSchema) { flags |= BinaryObjectHeader.Flag.HasSchema; // Calculate and write header. if (_frame.RawPos > 0) _stream.WriteInt(_frame.RawPos - pos); // raw offset is in the last 4 bytes // Update schema in type descriptor if (desc.Schema.Get(schemaId) == null) desc.Schema.Add(schemaId, _schema.GetSchema(schemaIdx)); } else schemaOffset = headerSize; if (_frame.RawPos > 0) flags |= BinaryObjectHeader.Flag.HasRaw; var len = _stream.Position - pos; var hashCode = BinaryArrayEqualityComparer.GetHashCode(Stream, pos + BinaryObjectHeader.Size, dataEnd - pos - BinaryObjectHeader.Size); var header = new BinaryObjectHeader(desc.IsRegistered ? desc.TypeId : BinaryTypeId.Unregistered, hashCode, len, schemaId, schemaOffset, flags); BinaryObjectHeader.Write(header, _stream, pos); if (OnObjectWritten != null) { OnObjectWritten(header, obj); } Stream.Seek(pos + len, SeekOrigin.Begin); // Seek to the end } finally { _schema.PopSchema(schemaIdx); } // Apply structure updates if any. _frame.Struct.UpdateWriterStructure(this); // Restore old frame. _frame = oldFrame; } /// <summary> /// Marks current object with a custom type data flag. /// </summary> public void SetCustomTypeDataFlag(bool hasCustomTypeData) { _frame.HasCustomTypeData = hasCustomTypeData; } /// <summary> /// Write primitive type. /// </summary> /// <param name="val">Object.</param> /// <param name="type">Type.</param> private unsafe void WritePrimitive<T>(T val, Type type) { // .NET defines 14 primitive types. // Types check sequence is designed to minimize comparisons for the most frequent types. if (type == typeof(int)) WriteIntField(TypeCaster<int>.Cast(val)); else if (type == typeof(long)) WriteLongField(TypeCaster<long>.Cast(val)); else if (type == typeof(bool)) WriteBooleanField(TypeCaster<bool>.Cast(val)); else if (type == typeof(byte)) WriteByteField(TypeCaster<byte>.Cast(val)); else if (type == typeof(short)) WriteShortField(TypeCaster<short>.Cast(val)); else if (type == typeof(char)) WriteCharField(TypeCaster<char>.Cast(val)); else if (type == typeof(float)) WriteFloatField(TypeCaster<float>.Cast(val)); else if (type == typeof(double)) WriteDoubleField(TypeCaster<double>.Cast(val)); else if (type == typeof(sbyte)) { var val0 = TypeCaster<sbyte>.Cast(val); WriteByteField(*(byte*)&val0); } else if (type == typeof(ushort)) { var val0 = TypeCaster<ushort>.Cast(val); WriteShortField(*(short*) &val0); } else if (type == typeof(uint)) { var val0 = TypeCaster<uint>.Cast(val); WriteIntField(*(int*)&val0); } else if (type == typeof(ulong)) { var val0 = TypeCaster<ulong>.Cast(val); WriteLongField(*(long*)&val0); } else if (type == typeof(IntPtr)) { var val0 = TypeCaster<IntPtr>.Cast(val).ToInt64(); WriteLongField(val0); } else if (type == typeof(UIntPtr)) { var val0 = TypeCaster<UIntPtr>.Cast(val).ToUInt64(); WriteLongField(*(long*)&val0); } else throw BinaryUtils.GetUnsupportedTypeException(type, val); } /// <summary> /// Try writing object as special builder type. /// </summary> /// <param name="obj">Object.</param> /// <returns>True if object was written, false otherwise.</returns> private bool WriteBuilderSpecials<T>(T obj) { if (_builder != null) { // Special case for binary object during build. BinaryObject portObj = obj as BinaryObject; if (portObj != null) { if (!WriteHandle(_stream.Position, portObj)) _builder.ProcessBinary(_stream, portObj); return true; } // Special case for builder during build. BinaryObjectBuilder portBuilder = obj as BinaryObjectBuilder; if (portBuilder != null) { if (!WriteHandle(_stream.Position, portBuilder)) _builder.ProcessBuilder(_stream, portBuilder); return true; } } return false; } /// <summary> /// Add handle to handles map. /// </summary> /// <param name="pos">Position in stream.</param> /// <param name="obj">Object.</param> /// <returns><c>true</c> if object was written as handle.</returns> private bool WriteHandle(long pos, object obj) { if (_hnds == null) { // Cache absolute handle position. _hnds = new BinaryHandleDictionary<object, long>(obj, pos, ReferenceEqualityComparer<object>.Instance); return false; } long hndPos; if (!_hnds.TryGetValue(obj, out hndPos)) { // Cache absolute handle position. _hnds.Add(obj, pos); return false; } _stream.WriteByte(BinaryUtils.HdrHnd); // Handle is written as difference between position before header and handle position. _stream.WriteInt((int)(pos - hndPos)); return true; } /// <summary> /// Perform action with detached semantics. /// </summary> internal void WriteObjectDetached<T>(T o) { if (_detaching) { Write(o); } else { _detaching = true; BinaryHandleDictionary<object, long> oldHnds = _hnds; _hnds = null; try { Write(o); } finally { _detaching = false; if (oldHnds != null) { // Merge newly recorded handles with old ones and restore old on the stack. // Otherwise we can use current handles right away. if (_hnds != null) oldHnds.Merge(_hnds); _hnds = oldHnds; } } } } /// <summary> /// Gets or sets a function to wrap all serializer objects. /// </summary> internal Func<object, object> WrapperFunc { get; set; } /// <summary> /// Stream. /// </summary> internal IBinaryStream Stream { get { return _stream; } } /// <summary> /// Gets collected metadatas. /// </summary> /// <returns>Collected metadatas (if any).</returns> internal ICollection<BinaryType> GetBinaryTypes() { return _metas == null ? null : _metas.Values; } /// <summary> /// Write field ID. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="fieldTypeId">Field type ID.</param> private void WriteFieldId(string fieldName, byte fieldTypeId) { if (_frame.RawPos != 0) throw new BinaryObjectException("Cannot write named fields after raw data is written."); var fieldId = _frame.Struct.GetFieldId(fieldName, fieldTypeId); _schema.PushField(fieldId, _stream.Position - _frame.Pos); } /// <summary> /// Saves metadata for this session. /// </summary> /// <param name="desc">The descriptor.</param> /// <param name="fields">Fields metadata.</param> internal void SaveMetadata(IBinaryTypeDescriptor desc, IDictionary<string, BinaryField> fields) { Debug.Assert(desc != null); if (!desc.UserType && (fields == null || fields.Count == 0)) { // System types with no fields (most of them) do not need to be sent. // AffinityKey is an example of system type with metadata. return; } if (_metas == null) { _metas = new Dictionary<int, BinaryType>(1) { {desc.TypeId, new BinaryType(desc, _marsh, fields)} }; } else { BinaryType meta; if (_metas.TryGetValue(desc.TypeId, out meta)) meta.UpdateFields(fields); else _metas[desc.TypeId] = new BinaryType(desc, _marsh, fields); } } /// <summary> /// Stores current writer stack frame. /// </summary> private struct Frame { /** Current object start position. */ public int Pos; /** Current raw position. */ public int RawPos; /** Current type structure tracker. */ public BinaryStructureTracker Struct; /** Custom type data. */ public bool HasCustomTypeData; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.EventHub { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Azure Event Hubs client /// </summary> public partial class EventHubManagementClient : ServiceClient<EventHubManagementClient>, IEventHubManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Subscription credentials that uniquely identify a Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client API Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IOperations. /// </summary> public virtual IOperations Operations { get; private set; } /// <summary> /// Gets the INamespacesOperations. /// </summary> public virtual INamespacesOperations Namespaces { get; private set; } /// <summary> /// Gets the IEventHubsOperations. /// </summary> public virtual IEventHubsOperations EventHubs { get; private set; } /// <summary> /// Gets the IConsumerGroupsOperations. /// </summary> public virtual IConsumerGroupsOperations ConsumerGroups { get; private set; } /// <summary> /// Initializes a new instance of the EventHubManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected EventHubManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the EventHubManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected EventHubManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the EventHubManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected EventHubManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the EventHubManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected EventHubManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the EventHubManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public EventHubManagementClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the EventHubManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public EventHubManagementClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the EventHubManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public EventHubManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the EventHubManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public EventHubManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Operations = new Operations(this); Namespaces = new NamespacesOperations(this); EventHubs = new EventHubsOperations(this); ConsumerGroups = new ConsumerGroupsOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2015-08-01"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.IO; using System.Text; using System.Drawing; using System.Web; using System.Web.UI; using System.ComponentModel; using System.Collections; using System.Collections.Specialized; using System.Web.UI.WebControls; namespace NotAClue.Web.UI.BootstrapWebControls { #region wwWebTabControl /// <summary> /// Summary description for wwWebTabControl. /// </summary> [ToolboxData("<{0}:wwWebTabControl runat=server></{0}:wwWebTabControl>")] [ToolboxBitmap(typeof(System.Web.UI.WebControls.Image))] [ParseChildren(true)] [PersistChildren(false)] public class wwWebTabControl : Control { /// <summary> /// Collection of Tabpages. /// </summary> //[Bindable(true)] //[NotifyParentProperty(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] // Content generates code for each page [PersistenceMode(PersistenceMode.InnerProperty)] public TabPageCollection TabPages { get { return Tabs; } } private TabPageCollection Tabs = new TabPageCollection(); /// <summary> /// The completed control output /// </summary> private string Output = ""; /// <summary> /// The output for the tabs generated by RenderTabs /// </summary> private string TabOutput = ""; /// <summary> /// The output of the Script block required to handle tab activation /// </summary> private string Script = ""; protected System.Web.UI.WebControls.Literal txtActivationScript; protected System.Web.UI.WebControls.Literal txtTabPlaceHolder; private new bool DesignMode = (HttpContext.Current == null); /// <summary> /// The Selected Tab. Set this to the TabPageClientId of the tab that you want to have selected /// </summary> [Browsable(true), Description("The TabPageClientId of the selected tab. This TabPageClientId must map to TabPageClientId assigned to a tab. Should also match an ID tag in the doc that is shown or hidden when tab is activated.")] public string SelectedTab { get { return this.cSelectedTab; } set { this.cSelectedTab = value; } } string cSelectedTab = ""; /// <summary> /// The width for each of the tabs. Each tab will be this width. /// </summary> [Browsable(true), Description("The width of all the individual tabs in pixels"), DefaultValue(110)] public int TabWidth { get { return this._TabWidth; } set { this._TabWidth = value; } } int _TabWidth = 110; /// <summary> /// The height of each of the tabs. /// </summary> [Browsable(true), Description("The Height of all the individual tabs in pixels"), DefaultValue(25)] public int TabHeight { get { return this._TabHeight; } set { this._TabHeight = value; } } int _TabHeight = 25; /// <summary> /// The CSS class that is used to render a selected button. Defaults to selectedtabbutton. /// </summary> [Browsable(true), Description("The CSS style used for the selected tab"), DefaultValue("selectedtabbutton")] public string SelectedTabCssClass { get { return this.cSelectedTabCssClass; } set { this.cSelectedTabCssClass = value; } } string cSelectedTabCssClass = "selectedtabbutton"; /// <summary> /// The CSS class that is used to render nonselected tabs. /// </summary> [Browsable(true), Description("The CSS style used for non selected tabs"), DefaultValue("tabbutton")] public string TabCssClass { get { return this.cTabCssClass; } set { this.cTabCssClass = value; } } string cTabCssClass = "tabbutton"; protected override void OnLoad(EventArgs e) { // *** Handle the Selected Tab Postback operation if (this.Page.IsPostBack) // && !this.TabSelected) { string TabSelection = this.Page.Request.Form["wwClientTabControlSelection_" + this.ID]; if (TabSelection != "") this.SelectedTab = TabSelection; } base.OnLoad(e); } protected override void Render(HtmlTextWriter writer) { bool NoTabs = false; string Selected = null; // *** If no tabs have been defined in design mode write a canned HTML display if (this.DesignMode && (this.TabPages == null || this.TabPages.Count == 0)) { NoTabs = true; this.AddTab("No Tabs", "default", "Tab1"); this.AddTab("No Tabs 2", "default", "Tab2"); Selected = this.SelectedTab; this.SelectedTab = "Tab2"; } // *** Render the actual control this.RenderControl(); // *** Dump the output into the ASP out stream writer.Write(this.Output); // *** Call the base to let it output the writer's output base.Render(writer); if (NoTabs) { this.TabPages.Clear(); this.SelectedTab = Selected; } } /// <summary> /// High level routine that /// </summary> private void RenderControl() { // *** Generate the HTML for the tabs and script blocks this.RenderTabs(); // *** Generate the HTML for the base page and embed // *** the script etc into the page this.Output = string.Format(wwWebTabControl.MasterTemplate, this.TabOutput, this.Script, this.SelectedTabCssClass); // *** Persist our selection into a hidden var since it's all client side // *** Script updates this var this.Page.RegisterHiddenField("wwClientTabControlSelection_" + this.ID, this.SelectedTab); // *** Force the page to show the Selected Tab if (this.cSelectedTab != "") this.Page.RegisterStartupScript("wwWebTabControl_Startup", "<script language='javascript'>ShowTabPage('" + this.SelectedTab + "');</script>"); } /// <summary> /// Creates various string properties that are merged into the output template. /// Creates the tabs and the associated script code. /// </summary> private void RenderTabs() { if (this.Tabs != null) { // *** ActivateTab script code StringBuilder Script = new StringBuilder(); // *** ShowTabPage script code StringBuilder Script2 = new StringBuilder(); // *** HtmlTextWriter to handle output generation for the HTML StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); HtmlTextWriter TabWriter = new HtmlTextWriter(sw); Script.Append( @" <script> function ActivateTab(object) { PageName = object.id; "); Script2.Append(@"function ShowTabPage(PageName) { "); TabWriter.Write("<table border='0' cellspacing='0'><tr>"); int Count = 0; foreach (TabPage Tab in this.Tabs) { Count++; string Id = this.ID + "_" + Count; TabWriter.WriteBeginTag("td"); TabWriter.WriteAttribute("height", this.TabHeight.ToString() + "px"); TabWriter.WriteAttribute("width", this.TabWidth.ToString() + "px"); TabWriter.WriteAttribute("ID", Id); string ActionLink = this.FixupActionLink(Tab); if (ActionLink != "") TabWriter.WriteAttribute("onclick", ActionLink); if (this.Tabs == null) return; if (Tab.TabPageClientId != "" && Tab.TabPageClientId == this.cSelectedTab) TabWriter.WriteAttribute("class", this.SelectedTabCssClass); else TabWriter.WriteAttribute("class", this.TabCssClass); TabWriter.Write(HtmlTextWriter.TagRightChar); TabWriter.Write(Tab.Caption); TabWriter.WriteEndTag("td"); TabWriter.Write("\r\n"); Script.Append("document.getElementById('" + Id + "').className='tabbutton';\r\n"); // *** If we have a TabPageClientId we need the page to be udpateable // *** through a matching ID tag. if (Tab.TabPageClientId != "") Script2.Append("document.getElementById('" + Tab.TabPageClientId + "').style.display='none'\r\n"); } TabWriter.Write("</tr></table>"); Script.Append("document.getElementById(PageName).className='selectedtabbutton';\r\n"); Script2.Append("document.getElementById(PageName).style.display='';\r\n"); Script2.Append("document.getElementById('wwClientTabControlSelection_" + this.ID + "').value=PageName;\r\n"); this.TabOutput = sb.ToString(); TabWriter.Close(); Script.Append("}\r\n"); Script.Append(Script2.ToString() + "}\r\n"); Script.Append("</script>\r\n"); this.Script = Script.ToString(); } } /// <summary> /// Adds a new item to the Tab collection. /// </summary> /// <param name="Caption">The caption of the tab</param> /// <param name="Link">The HTTP or JavaScript link that is fired when the tab is activated. Can optionally be Default which activates the tab and activates the page ID.</param> /// <param name="TabPageClientId">The ID for this tab - map this to an ID tag in the HTML form.</param> public void AddTab(string Caption, string Link, string TabPageClientId) { TabPage Tab = new TabPage(); Tab.Caption = Caption; Tab.ActionLink = Link; Tab.TabPageClientId = TabPageClientId; this.AddTab(Tab); } /// <summary> /// Adds a new item to the Tab collection. /// </summary> /// <param name="Caption">The caption of the tab</param> /// <param name="Link">The HTTP or JavaScript link that is fired when the tab is activated. Can optionally be Default which activates the tab and activates the page ID.</param> public void AddTab(string Caption, string Link) { this.AddTab(Caption, Link, ""); } public void AddTab(TabPage Tab) { this.Tabs.Add(Tab); } /// <summary> /// Fixes up the ActionLink property to final script code /// suitable for an onclick handler /// </summary> /// <returns></returns> protected string FixupActionLink(TabPage Tab) { string Action = Tab.ActionLink; if (Action.ToLower() == "default") Action = "javascript:ActivateTab(this);ShowTabPage('" + Tab.TabPageClientId + "');"; // *** If we don't have 'javascript:' in the text it's a Url: must use document to go there if (Action != "" && Action.IndexOf("script:") < 0) Action = "document.location='" + Action + "';"; return Action; } /// <summary> /// Required to be able to properly deal with the Collection object /// </summary> /// <param name="obj"></param> protected override void AddParsedSubObject(object obj) { if (obj is TabPage) { this.TabPages.Add((TabPage)obj); return; } } /// <summary> /// The master HTML template into which the dynamically generated tab display is rendered. /// </summary> private static string MasterTemplate = @" {1} <table width='100%' border='0' cellspacing='0' cellpadding='0'> <tr> <td>{0}</td> </tr> <tr> <td class='{2}' height='3'></td> </tr> </table> "; } #endregion #region TabPage Class /// <summary> /// The individual TabPage class that holds the intermediary Tab page values /// </summary> [ToolboxData("<{0}:TabPage runat=server></{0}:TabPage>")] public class TabPage : Control { [NotifyParentProperty(true)] [Browsable(true), Description("The display caption for the Tab.")] public string Caption { get { return cCaption; } set { cCaption = value; } } string cCaption = ""; [NotifyParentProperty(true)] [Browsable(true), Description("The TabPageClientId for this item. If you create a TabPageClientId you must create a matching ID tag in your HTML that is to be enabled and disabled automatically.")] public string TabPageClientId { get { return cTabPageClientId; } set { cTabPageClientId = value; } } string cTabPageClientId = ""; [NotifyParentProperty(true)] [Browsable(true), Description("The Url or javascript: code that fires. You can use javascript:ActivateTab(this);ShowPage('TabPageClientIdValue'); to force a tab and page to display.")] public string ActionLink { get { return Href; } set { Href = value; } } string Href = ""; // [NotifyParentProperty(true)] // [Browsable(true),Description("Determines whether this tab shows as selected.")] // public bool Selected // { // get { return this.bSelected; } // set { // this.bSelected = value; // if (this.Parent != null) // { // ((wwWebTabControl) this.Parent).SelectedTab = this.TabPageClientId; // } // } // // } // bool bSelected = false; } #endregion #region TabPageCollection Class /// <summary> /// Holds a collection of Tab Pages /// </summary> public class TabPageCollection : CollectionBase { public TabPageCollection() { } /// <summary> /// Indexer property for the collection that returns and sets an item /// </summary> public TabPage this[int index] { get { return (TabPage)this.List[index]; } set { this.List[index] = value; } } /// <summary> /// Adds a new error to the collection /// </summary> public void Add(TabPage Tab) { this.List.Add(Tab); } public void Insert(int index, TabPage item) { this.List.Insert(index, item); } public void Remove(TabPage Tab) { List.Remove(Tab); } public bool Contains(TabPage Tab) { return this.List.Contains(Tab); } //Collection IndexOf method public int IndexOf(TabPage item) { return List.IndexOf(item); } public void CopyTo(TabPage[] array, int index) { List.CopyTo(array, index); } } #endregion }
//----------------------------------------------------------------------- // <copyright file="ActorPublisher.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.Serialization; using Akka.Actor; using Akka.Event; using Akka.Pattern; using Akka.Util; using Reactive.Streams; namespace Akka.Streams.Implementation { [Serializable] internal sealed class SubscribePending { public static readonly SubscribePending Instance = new SubscribePending(); private SubscribePending() { } } [Serializable] internal sealed class RequestMore : IDeadLetterSuppression { public readonly IActorSubscription Subscription; public readonly long Demand; public RequestMore(IActorSubscription subscription, long demand) { Subscription = subscription; Demand = demand; } } [Serializable] internal sealed class Cancel : IDeadLetterSuppression { public readonly IActorSubscription Subscription; public Cancel(IActorSubscription subscription) { Subscription = subscription; } } [Serializable] internal sealed class ExposedPublisher : IDeadLetterSuppression { public readonly IActorPublisher Publisher; public ExposedPublisher(IActorPublisher publisher) { Publisher = publisher; } } [Serializable] public class NormalShutdownException : IllegalStateException { public NormalShutdownException(string message) : base(message) { } protected NormalShutdownException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal interface IActorPublisher : IUntypedPublisher { void Shutdown(Exception reason); IEnumerable<IUntypedSubscriber> TakePendingSubscribers(); } internal static class ActorPublisher { public const string NormalShutdownReasonMessage = "Cannot subscribe to shut-down Publisher"; public static readonly NormalShutdownException NormalShutdownReason = new NormalShutdownException(NormalShutdownReasonMessage); } /// <summary> /// INTERNAL API /// /// When you instantiate this class, or its subclasses, you MUST send an ExposedPublisher message to the wrapped /// ActorRef! If you don't need to subclass, prefer the apply() method on the companion object which takes care of this. /// </summary> public class ActorPublisher<TOut> : IActorPublisher, IPublisher<TOut> { protected readonly IActorRef Impl; // The subscriber of an subscription attempt is first placed in this list of pending subscribers. // The actor will call takePendingSubscribers to remove it from the list when it has received the // SubscribePending message. The AtomicReference is set to null by the shutdown method, which is // called by the actor from postStop. Pending (unregistered) subscription attempts are denied by // the shutdown method. Subscription attempts after shutdown can be denied immediately. private readonly AtomicReference<ImmutableList<ISubscriber<TOut>>> _pendingSubscribers = new AtomicReference<ImmutableList<ISubscriber<TOut>>>(ImmutableList<ISubscriber<TOut>>.Empty); private volatile Exception _shutdownReason; protected virtual object WakeUpMessage => SubscribePending.Instance; public ActorPublisher(IActorRef impl) { Impl = impl; } public void Subscribe(ISubscriber<TOut> subscriber) { if (subscriber == null) throw new ArgumentNullException(nameof(subscriber)); while (true) { var current = _pendingSubscribers.Value; if (current == null) { ReportSubscribeFailure(subscriber); break; } if (_pendingSubscribers.CompareAndSet(current, current.Add(subscriber))) { Impl.Tell(WakeUpMessage); break; } } } void IUntypedPublisher.Subscribe(IUntypedSubscriber subscriber) => Subscribe(UntypedSubscriber.ToTyped<TOut>(subscriber)); public IEnumerable<ISubscriber<TOut>> TakePendingSubscribers() { var pending = _pendingSubscribers.GetAndSet(ImmutableList<ISubscriber<TOut>>.Empty); return pending ?? ImmutableList<ISubscriber<TOut>>.Empty; } IEnumerable<IUntypedSubscriber> IActorPublisher.TakePendingSubscribers() => TakePendingSubscribers().Select(UntypedSubscriber.FromTyped); public void Shutdown(Exception reason) { _shutdownReason = reason; var pending = _pendingSubscribers.GetAndSet(null); if (pending != null) { foreach (var subscriber in pending.Reverse()) ReportSubscribeFailure(subscriber); } } private void ReportSubscribeFailure(ISubscriber<TOut> subscriber) { try { if (_shutdownReason == null) { ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance); ReactiveStreamsCompliance.TryOnComplete(subscriber); } else if (_shutdownReason is ISpecViolation) { // ok, not allowed to call OnError } else { ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance); ReactiveStreamsCompliance.TryOnError(subscriber, _shutdownReason); } } catch (Exception exception) { if (!(exception is ISpecViolation)) throw; } } } public interface IActorSubscription : ISubscription { } public static class ActorSubscription { internal static IActorSubscription Create(IActorRef implementor, IUntypedSubscriber subscriber) { var subscribedType = subscriber.GetType().GetGenericArguments().First(); // assumes type is UntypedSubscriberWrapper var subscriptionType = typeof(ActorSubscription<>).MakeGenericType(subscribedType); return (IActorSubscription) Activator.CreateInstance(subscriptionType, implementor, UntypedSubscriber.ToTyped(subscriber)); } public static IActorSubscription Create<T>(IActorRef implementor, ISubscriber<T> subscriber) => new ActorSubscription<T>(implementor, subscriber); } public class ActorSubscription<T> : IActorSubscription { public readonly IActorRef Implementor; public readonly ISubscriber<T> Subscriber; public ActorSubscription(IActorRef implementor, ISubscriber<T> subscriber) { Implementor = implementor; Subscriber = subscriber; } public void Request(long n) => Implementor.Tell(new RequestMore(this, n)); public void Cancel() => Implementor.Tell(new Cancel(this)); } public class ActorSubscriptionWithCursor<TIn> : ActorSubscription<TIn>, ISubscriptionWithCursor<TIn> { public ActorSubscriptionWithCursor(IActorRef implementor, ISubscriber<TIn> subscriber) : base(implementor, subscriber) { IsActive = true; TotalDemand = 0; Cursor = 0; } ISubscriber<TIn> ISubscriptionWithCursor<TIn>.Subscriber => Subscriber; public void Dispatch(object element) => ReactiveStreamsCompliance.TryOnNext(Subscriber, (TIn)element); bool ISubscriptionWithCursor<TIn>.IsActive { get { return IsActive; } set { IsActive = value; } } public bool IsActive { get; private set; } public int Cursor { get; private set; } long ISubscriptionWithCursor<TIn>.TotalDemand { get { return TotalDemand; } set { TotalDemand = value; } } public long TotalDemand { get; private set; } public void Dispatch(TIn element) => ReactiveStreamsCompliance.TryOnNext(Subscriber, element); int ICursor.Cursor { get { return Cursor; } set { Cursor = value; } } } }
namespace android.view { [global::MonoJavaBridge.JavaClass()] public partial class GestureDetector : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected GestureDetector(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.GestureDetector.OnDoubleTapListener_))] public partial interface OnDoubleTapListener : global::MonoJavaBridge.IJavaObject { bool onSingleTapConfirmed(android.view.MotionEvent arg0); bool onDoubleTap(android.view.MotionEvent arg0); bool onDoubleTapEvent(android.view.MotionEvent arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.GestureDetector.OnDoubleTapListener))] internal sealed partial class OnDoubleTapListener_ : java.lang.Object, OnDoubleTapListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnDoubleTapListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; bool android.view.GestureDetector.OnDoubleTapListener.onSingleTapConfirmed(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, "onSingleTapConfirmed", "(Landroid/view/MotionEvent;)Z", ref global::android.view.GestureDetector.OnDoubleTapListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; bool android.view.GestureDetector.OnDoubleTapListener.onDoubleTap(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, "onDoubleTap", "(Landroid/view/MotionEvent;)Z", ref global::android.view.GestureDetector.OnDoubleTapListener_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; bool android.view.GestureDetector.OnDoubleTapListener.onDoubleTapEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, "onDoubleTapEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.view.GestureDetector.OnDoubleTapListener_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } static OnDoubleTapListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.OnDoubleTapListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector$OnDoubleTapListener")); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.GestureDetector.OnGestureListener_))] public partial interface OnGestureListener : global::MonoJavaBridge.IJavaObject { void onLongPress(android.view.MotionEvent arg0); bool onSingleTapUp(android.view.MotionEvent arg0); bool onScroll(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3); bool onFling(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3); void onShowPress(android.view.MotionEvent arg0); bool onDown(android.view.MotionEvent arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.GestureDetector.OnGestureListener))] internal sealed partial class OnGestureListener_ : java.lang.Object, OnGestureListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnGestureListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.view.GestureDetector.OnGestureListener.onLongPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.GestureDetector.OnGestureListener_.staticClass, "onLongPress", "(Landroid/view/MotionEvent;)V", ref global::android.view.GestureDetector.OnGestureListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; bool android.view.GestureDetector.OnGestureListener.onSingleTapUp(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.OnGestureListener_.staticClass, "onSingleTapUp", "(Landroid/view/MotionEvent;)Z", ref global::android.view.GestureDetector.OnGestureListener_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; bool android.view.GestureDetector.OnGestureListener.onScroll(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.OnGestureListener_.staticClass, "onScroll", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z", ref global::android.view.GestureDetector.OnGestureListener_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m3; bool android.view.GestureDetector.OnGestureListener.onFling(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.OnGestureListener_.staticClass, "onFling", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z", ref global::android.view.GestureDetector.OnGestureListener_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m4; void android.view.GestureDetector.OnGestureListener.onShowPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.GestureDetector.OnGestureListener_.staticClass, "onShowPress", "(Landroid/view/MotionEvent;)V", ref global::android.view.GestureDetector.OnGestureListener_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; bool android.view.GestureDetector.OnGestureListener.onDown(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.OnGestureListener_.staticClass, "onDown", "(Landroid/view/MotionEvent;)Z", ref global::android.view.GestureDetector.OnGestureListener_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } static OnGestureListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.OnGestureListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector$OnGestureListener")); } } [global::MonoJavaBridge.JavaClass()] public partial class SimpleOnGestureListener : java.lang.Object, OnGestureListener, OnDoubleTapListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected SimpleOnGestureListener(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public virtual void onLongPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onLongPress", "(Landroid/view/MotionEvent;)V", ref global::android.view.GestureDetector.SimpleOnGestureListener._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public virtual bool onSingleTapConfirmed(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onSingleTapConfirmed", "(Landroid/view/MotionEvent;)Z", ref global::android.view.GestureDetector.SimpleOnGestureListener._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; public virtual bool onDoubleTap(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onDoubleTap", "(Landroid/view/MotionEvent;)Z", ref global::android.view.GestureDetector.SimpleOnGestureListener._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public virtual bool onDoubleTapEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onDoubleTapEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.view.GestureDetector.SimpleOnGestureListener._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m4; public virtual bool onSingleTapUp(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onSingleTapUp", "(Landroid/view/MotionEvent;)Z", ref global::android.view.GestureDetector.SimpleOnGestureListener._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public virtual bool onScroll(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onScroll", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z", ref global::android.view.GestureDetector.SimpleOnGestureListener._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m6; public virtual bool onFling(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onFling", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z", ref global::android.view.GestureDetector.SimpleOnGestureListener._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m7; public virtual void onShowPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onShowPress", "(Landroid/view/MotionEvent;)V", ref global::android.view.GestureDetector.SimpleOnGestureListener._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m8; public virtual bool onDown(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onDown", "(Landroid/view/MotionEvent;)Z", ref global::android.view.GestureDetector.SimpleOnGestureListener._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m9; public SimpleOnGestureListener() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.GestureDetector.SimpleOnGestureListener._m9.native == global::System.IntPtr.Zero) global::android.view.GestureDetector.SimpleOnGestureListener._m9 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._m9); Init(@__env, handle); } static SimpleOnGestureListener() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.SimpleOnGestureListener.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector$SimpleOnGestureListener")); } } private static global::MonoJavaBridge.MethodId _m0; public virtual bool onTouchEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.view.GestureDetector._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public virtual void setOnDoubleTapListener(android.view.GestureDetector.OnDoubleTapListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.GestureDetector.staticClass, "setOnDoubleTapListener", "(Landroid/view/GestureDetector$OnDoubleTapListener;)V", ref global::android.view.GestureDetector._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; public virtual void setIsLongpressEnabled(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.GestureDetector.staticClass, "setIsLongpressEnabled", "(Z)V", ref global::android.view.GestureDetector._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public virtual bool isLongpressEnabled() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.GestureDetector.staticClass, "isLongpressEnabled", "()Z", ref global::android.view.GestureDetector._m3); } private static global::MonoJavaBridge.MethodId _m4; public GestureDetector(android.view.GestureDetector.OnGestureListener arg0, android.os.Handler arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.GestureDetector._m4.native == global::System.IntPtr.Zero) global::android.view.GestureDetector._m4 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/view/GestureDetector$OnGestureListener;Landroid/os/Handler;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m5; public GestureDetector(android.view.GestureDetector.OnGestureListener arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.GestureDetector._m5.native == global::System.IntPtr.Zero) global::android.view.GestureDetector._m5 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/view/GestureDetector$OnGestureListener;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m6; public GestureDetector(android.content.Context arg0, android.view.GestureDetector.OnGestureListener arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.GestureDetector._m6.native == global::System.IntPtr.Zero) global::android.view.GestureDetector._m6 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/content/Context;Landroid/view/GestureDetector$OnGestureListener;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m7; public GestureDetector(android.content.Context arg0, android.view.GestureDetector.OnGestureListener arg1, android.os.Handler arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.GestureDetector._m7.native == global::System.IntPtr.Zero) global::android.view.GestureDetector._m7 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/content/Context;Landroid/view/GestureDetector$OnGestureListener;Landroid/os/Handler;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m8; public GestureDetector(android.content.Context arg0, android.view.GestureDetector.OnGestureListener arg1, android.os.Handler arg2, bool arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.GestureDetector._m8.native == global::System.IntPtr.Zero) global::android.view.GestureDetector._m8 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/content/Context;Landroid/view/GestureDetector$OnGestureListener;Landroid/os/Handler;Z)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); Init(@__env, handle); } static GestureDetector() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector")); } } }
// 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.CognitiveServices.Vision.Face { using Microsoft.Azure; using Microsoft.Azure.CognitiveServices; using Microsoft.Azure.CognitiveServices.Vision; using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// FaceList operations. /// </summary> public partial interface IFaceList { /// <summary> /// Create an empty face list. Up to 64 face lists are allowed to exist /// in one subscription. /// </summary> /// <param name='faceListId'> /// Id referencing a particular face list. /// </param> /// <param name='name'> /// Name of the face list, maximum length is 128. /// </param> /// <param name='userData'> /// Optional user defined data for the face list. Length should not /// exceed 16KB. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> CreateWithHttpMessagesAsync(string faceListId, string name = default(string), string userData = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieve a face list's information. /// </summary> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<GetFaceListResult>> GetWithHttpMessagesAsync(string faceListId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update information of a face list. /// </summary> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='name'> /// Name of the face list, maximum length is 128. /// </param> /// <param name='userData'> /// Optional user defined data for the face list. Length should not /// exceed 16KB. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> UpdateWithHttpMessagesAsync(string faceListId, string name = default(string), string userData = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an existing face list according to faceListId. Persisted /// face images in the face list will also be deleted. /// </summary> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string faceListId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieve information about all existing face lists. Only /// faceListId, name and userData will be returned. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<IList<GetFaceListResult>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an existing face from a face list (given by a /// persisitedFaceId and a faceListId). Persisted image related to the /// face will also be deleted. /// </summary> /// <param name='faceListId'> /// faceListId of an existing face list. /// </param> /// <param name='persistedFaceId'> /// persistedFaceId of an existing face. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> DeleteFaceWithHttpMessagesAsync(string faceListId, string persistedFaceId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Add a face to a face list. The input face is specified as an image /// with a targetFace rectangle. It returns a persistedFaceId /// representing the added face, and persistedFaceId will not expire. /// </summary> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='userData'> /// User-specified data about the face list for any purpose. The /// maximum length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added into the /// face list, in the format of "targetFace=left,top,width,height". /// E.g. "targetFace=10,10,100,100". If there is more than one face in /// the image, targetFace is required to specify which face to add. No /// targetFace means there is only one face detected in the entire /// image. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> AddFaceWithHttpMessagesAsync(string faceListId, string userData = default(string), string targetFace = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Add a face to a face list. The input face is specified as an image /// with a targetFace rectangle. It returns a persistedFaceId /// representing the added face, and persistedFaceId will not expire. /// </summary> /// <param name='faceListId'> /// Id referencing a Face List. /// </param> /// <param name='userData'> /// User-specified data about the face list for any purpose. The /// maximum length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added into the /// face list, in the format of "targetFace=left,top,width,height". /// E.g. "targetFace=10,10,100,100". If there is more than one face in /// the image, targetFace is required to specify which face to add. No /// targetFace means there is only one face detected in the entire /// image. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> AddFaceFromStreamWithHttpMessagesAsync(string faceListId, string userData = default(string), string targetFace = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1995 { /// <summary> /// Section 5.2.8. Time measurements that exceed one hour. Hours is the number of hours since January 1, 1970, UTC /// </summary> [Serializable] [XmlRoot] public partial class ClockTime { /// <summary> /// Hours in UTC /// </summary> private int _hour; /// <summary> /// Time past the hour /// </summary> private uint _timePastHour; /// <summary> /// Initializes a new instance of the <see cref="ClockTime"/> class. /// </summary> public ClockTime() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(ClockTime left, ClockTime right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(ClockTime left, ClockTime right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 4; // this._hour marshalSize += 4; // this._timePastHour return marshalSize; } /// <summary> /// Gets or sets the Hours in UTC /// </summary> [XmlElement(Type = typeof(int), ElementName = "hour")] public int Hour { get { return this._hour; } set { this._hour = value; } } /// <summary> /// Gets or sets the Time past the hour /// </summary> [XmlElement(Type = typeof(uint), ElementName = "timePastHour")] public uint TimePastHour { get { return this._timePastHour; } set { this._timePastHour = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { dos.WriteInt((int)this._hour); dos.WriteUnsignedInt((uint)this._timePastHour); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { this._hour = dis.ReadInt(); this._timePastHour = dis.ReadUnsignedInt(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<ClockTime>"); try { sb.AppendLine("<hour type=\"int\">" + this._hour.ToString(CultureInfo.InvariantCulture) + "</hour>"); sb.AppendLine("<timePastHour type=\"uint\">" + this._timePastHour.ToString(CultureInfo.InvariantCulture) + "</timePastHour>"); sb.AppendLine("</ClockTime>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as ClockTime; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(ClockTime obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (this._hour != obj._hour) { ivarsEqual = false; } if (this._timePastHour != obj._timePastHour) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ this._hour.GetHashCode(); result = GenerateHash(result) ^ this._timePastHour.GetHashCode(); return result; } } }
#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.Diagnostics; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Runtime.Serialization; using System.Text; using System.Xml; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests { [TestFixture] public class JsonTextWriterTest : TestFixtureBase { [Test] public void NewLine() { MemoryStream ms = new MemoryStream(); using (var streamWriter = new StreamWriter(ms, new UTF8Encoding(false)) { NewLine = "\n" }) using (var jsonWriter = new JsonTextWriter(streamWriter) { CloseOutput = true, Indentation = 2, Formatting = Formatting.Indented }) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("prop"); jsonWriter.WriteValue(true); jsonWriter.WriteEndObject(); } byte[] data = ms.ToArray(); string json = Encoding.UTF8.GetString(data, 0, data.Length); Assert.AreEqual(@"{" + '\n' + @" ""prop"": true" + '\n' + "}", json); } [Test] public void QuoteNameAndStrings() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonTextWriter writer = new JsonTextWriter(sw) { QuoteName = false }; writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("value"); writer.WriteEndObject(); writer.Flush(); Assert.AreEqual(@"{name:""value""}", sb.ToString()); } [Test] public void CloseOutput() { MemoryStream ms = new MemoryStream(); JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms)); Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsFalse(ms.CanRead); ms = new MemoryStream(); writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false }; Assert.IsTrue(ms.CanRead); writer.Close(); Assert.IsTrue(ms.CanRead); } #if !(PORTABLE) [Test] public void WriteIConvertable() { var sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(new ConvertibleInt(1)); Assert.AreEqual("1", sw.ToString()); } #endif [Test] public void ValueFormatting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue('@'); jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'"); jsonWriter.WriteValue(true); jsonWriter.WriteValue(10); jsonWriter.WriteValue(10.99); jsonWriter.WriteValue(0.99); jsonWriter.WriteValue(0.000000000000000001d); jsonWriter.WriteValue(0.000000000000000001m); jsonWriter.WriteValue((string)null); jsonWriter.WriteValue((object)null); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteUndefined(); jsonWriter.WriteEndArray(); } string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void NullableValueFormatting() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue((char?)null); jsonWriter.WriteValue((char?)'c'); jsonWriter.WriteValue((bool?)null); jsonWriter.WriteValue((bool?)true); jsonWriter.WriteValue((byte?)null); jsonWriter.WriteValue((byte?)1); jsonWriter.WriteValue((sbyte?)null); jsonWriter.WriteValue((sbyte?)1); jsonWriter.WriteValue((short?)null); jsonWriter.WriteValue((short?)1); jsonWriter.WriteValue((ushort?)null); jsonWriter.WriteValue((ushort?)1); jsonWriter.WriteValue((int?)null); jsonWriter.WriteValue((int?)1); jsonWriter.WriteValue((uint?)null); jsonWriter.WriteValue((uint?)1); jsonWriter.WriteValue((long?)null); jsonWriter.WriteValue((long?)1); jsonWriter.WriteValue((ulong?)null); jsonWriter.WriteValue((ulong?)1); jsonWriter.WriteValue((double?)null); jsonWriter.WriteValue((double?)1.1); jsonWriter.WriteValue((float?)null); jsonWriter.WriteValue((float?)1.1); jsonWriter.WriteValue((decimal?)null); jsonWriter.WriteValue((decimal?)1.1m); jsonWriter.WriteValue((DateTime?)null); jsonWriter.WriteValue((DateTime?)new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc)); #if !NET20 jsonWriter.WriteValue((DateTimeOffset?)null); jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero)); #endif jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected; #if !NET20 expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]"; #else expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]"; #endif Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithNullable() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { char? value = 'c'; jsonWriter.WriteStartArray(); jsonWriter.WriteValue((object)value); jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected = @"[""c""]"; Assert.AreEqual(expected, json); } [Test] public void WriteValueObjectWithUnsupportedValue() { ExceptionAssert.Throws<JsonWriterException>(() => { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(new Version(1, 1, 1, 1)); jsonWriter.WriteEndArray(); } }, @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''."); } [Test] public void StringEscaping() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(@"""These pretzels are making me thirsty!"""); jsonWriter.WriteValue("Jeff's house was burninated."); jsonWriter.WriteValue("1. You don't talk about fight club.\r\n2. You don't talk about fight club."); jsonWriter.WriteValue("35% of\t statistics\n are made\r up."); jsonWriter.WriteEndArray(); } string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteEnd() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void CloseWithRemainingContent() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.Close(); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Indenting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } // { // "CPU": "Intel", // "PSU": "500W", // "Drives": [ // "DVD read/writer" // /*(broken)*/, // "500 gigabyte hard drive", // "200 gigabype hard drive" // ] // } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void State() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); jsonWriter.WriteStartObject(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); jsonWriter.WritePropertyName("CPU"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WriteValue("Intel"); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("CPU", jsonWriter.Path); jsonWriter.WritePropertyName("Drives"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteStartArray(); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); jsonWriter.WriteValue("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual("Drives[0]", jsonWriter.Path); jsonWriter.WriteEnd(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual("Drives", jsonWriter.Path); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); Assert.AreEqual("", jsonWriter.Path); } } [Test] public void FloatingPointNonFiniteNumbers_Symbol() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ NaN, Infinity, -Infinity, NaN, Infinity, -Infinity ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_Zero() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.DefaultValue; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue((double?)double.NaN); jsonWriter.WriteValue((double?)double.PositiveInfinity); jsonWriter.WriteValue((double?)double.NegativeInfinity); jsonWriter.WriteValue((float?)float.NaN); jsonWriter.WriteValue((float?)float.PositiveInfinity); jsonWriter.WriteValue((float?)float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, null, null, null, null, null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_String() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ ""NaN"", ""Infinity"", ""-Infinity"", ""NaN"", ""Infinity"", ""-Infinity"" ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void FloatingPointNonFiniteNumbers_QuoteChar() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.QuoteChar = '\''; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 'NaN', 'Infinity', '-Infinity', 'NaN', 'Infinity', '-Infinity' ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInStart() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteRaw("[1,2,3,4,5]"); jsonWriter.WriteWhitespace(" "); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndArray(); } string expected = @"[1,2,3,4,5] [ NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } string expected = @"[ NaN,[1,2,3,4,5],[1,2,3,4,5], NaN ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteRawInObject() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]"); jsonWriter.WriteEnd(); } string expected = @"{""PropertyName"":[1,2,3,4,5]}"; string result = sb.ToString(); Assert.AreEqual(expected, result); } [Test] public void WriteToken() { JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]")); reader.Read(); reader.Read(); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteToken(reader); Assert.AreEqual("1", sw.ToString()); } [Test] public void WriteRawValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { int i = 0; string rawJson = "[1,2]"; jsonWriter.WriteStartObject(); while (i < 3) { jsonWriter.WritePropertyName("d" + i); jsonWriter.WriteRawValue(rawJson); i++; } jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString()); } [Test] public void WriteObjectNestedInConstructor() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("con"); jsonWriter.WriteStartConstructor("Ext.data.JsonStore"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("aa"); jsonWriter.WriteValue("aa"); jsonWriter.WriteEndObject(); jsonWriter.WriteEndConstructor(); jsonWriter.WriteEndObject(); } Assert.AreEqual(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString()); } [Test] public void WriteFloatingPointNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteValue(0f); jsonWriter.WriteValue(0.1); jsonWriter.WriteValue(1.0); jsonWriter.WriteValue(1.000001); jsonWriter.WriteValue(0.000001); jsonWriter.WriteValue(double.Epsilon); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.MaxValue); jsonWriter.WriteValue(double.MinValue); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); } [Test] public void WriteIntegerNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented }) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(int.MaxValue); jsonWriter.WriteValue(int.MinValue); jsonWriter.WriteValue(0); jsonWriter.WriteValue(-0); jsonWriter.WriteValue(9L); jsonWriter.WriteValue(9UL); jsonWriter.WriteValue(long.MaxValue); jsonWriter.WriteValue(long.MinValue); jsonWriter.WriteValue(ulong.MaxValue); jsonWriter.WriteValue(ulong.MinValue); jsonWriter.WriteEndArray(); } Console.WriteLine(sb.ToString()); StringAssert.AreEqual(@"[ 2147483647, -2147483648, 0, 0, 9, 9, 9223372036854775807, -9223372036854775808, 18446744073709551615, 0 ]", sb.ToString()); } [Test] public void WriteTokenDirect() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); jsonWriter.WriteToken(JsonToken.Integer, 1); jsonWriter.WriteToken(JsonToken.StartObject); jsonWriter.WriteToken(JsonToken.PropertyName, "string"); jsonWriter.WriteToken(JsonToken.Integer, int.MaxValue); jsonWriter.WriteToken(JsonToken.EndObject); jsonWriter.WriteToken(JsonToken.EndArray); } Assert.AreEqual(@"[1,{""string"":2147483647}]", sb.ToString()); } [Test] public void WriteTokenDirect_BadValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteToken(JsonToken.StartArray); ExceptionAssert.Throws<FormatException>(() => { jsonWriter.WriteToken(JsonToken.Integer, "three"); }, "Input string was not in a correct format."); ExceptionAssert.Throws<ArgumentNullException>(() => { jsonWriter.WriteToken(JsonToken.Integer); }, @"Value cannot be null. Parameter name: value"); } } [Test] public void BadWriteEndArray() { ExceptionAssert.Throws<JsonWriterException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray(); } }, "No token to close. Path ''."); } [Test] public void InvalidQuoteChar() { ExceptionAssert.Throws<ArgumentException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.QuoteChar = '*'; } }, @"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); } [Test] public void Indentation() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.Indentation = 5; Assert.AreEqual(5, jsonWriter.Indentation); jsonWriter.IndentChar = '_'; Assert.AreEqual('_', jsonWriter.IndentChar); jsonWriter.QuoteName = true; Assert.AreEqual(true, jsonWriter.QuoteName); jsonWriter.QuoteChar = '\''; Assert.AreEqual('\'', jsonWriter.QuoteChar); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("propertyName"); jsonWriter.WriteValue(double.NaN); jsonWriter.IndentChar = '?'; Assert.AreEqual('?', jsonWriter.IndentChar); jsonWriter.Indentation = 6; Assert.AreEqual(6, jsonWriter.Indentation); jsonWriter.WritePropertyName("prop2"); jsonWriter.WriteValue(123); jsonWriter.WriteEndObject(); } string expected = @"{ _____'propertyName': NaN, ??????'prop2': 123 }"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void WriteSingleBytes() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteValue(data); } string expected = @"""SGVsbG8gd29ybGQu"""; string result = sb.ToString(); Assert.AreEqual(expected, result); byte[] d2 = Convert.FromBase64String(result.Trim('"')); Assert.AreEqual(text, Encoding.UTF8.GetString(d2, 0, d2.Length)); } [Test] public void WriteBytesInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.AreEqual(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(data); jsonWriter.WriteValue(data); jsonWriter.WriteValue((object)data); jsonWriter.WriteValue((byte[])null); jsonWriter.WriteValue((Uri)null); jsonWriter.WriteEndArray(); } string expected = @"[ ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", null, null ]"; string result = sb.ToString(); StringAssert.AreEqual(expected, result); } [Test] public void Path() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartArray(); Assert.AreEqual("", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[0]", writer.Path); writer.WritePropertyName("Property1"); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1", writer.Path); writer.WriteValue(1); Assert.AreEqual("[0].Property1[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[0].Property1[1][0][0]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[0]", writer.Path); writer.WriteStartObject(); Assert.AreEqual("[1]", writer.Path); writer.WritePropertyName("Property2"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteStartConstructor("Constructor1"); Assert.AreEqual("[1].Property2", writer.Path); writer.WriteNull(); Assert.AreEqual("[1].Property2[0]", writer.Path); writer.WriteStartArray(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteValue(1); Assert.AreEqual("[1].Property2[1][0]", writer.Path); writer.WriteEnd(); Assert.AreEqual("[1].Property2[1]", writer.Path); writer.WriteEndObject(); Assert.AreEqual("[1]", writer.Path); writer.WriteEndArray(); Assert.AreEqual("", writer.Path); } StringAssert.AreEqual(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]", sb.ToString()); } [Test] public void BuildStateArray() { JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray(); var valueStates = JsonWriter.StateArrayTempate[7]; foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken))) { switch (valueToken) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: Assert.AreEqual(valueStates, stateArray[(int)valueToken], "Error for " + valueToken + " states."); break; } } } [Test] public void DateTimeZoneHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc }; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified)); Assert.AreEqual(@"""2000-01-01T01:01:01Z""", sw.ToString()); } [Test] public void HtmlStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeHtml }; string script = @"<script type=""text/javascript"">alert('hi');</script>"; writer.WriteValue(script); string json = sw.ToString(); Assert.AreEqual(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(script, reader.ReadAsString()); } [Test] public void NonAsciiStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }; string unicode = "\u5f20"; writer.WriteValue(unicode); string json = sw.ToString(); Assert.AreEqual(8, json.Length); Assert.AreEqual(@"""\u5f20""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.AreEqual(unicode, reader.ReadAsString()); sw = new StringWriter(); writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.Default }; writer.WriteValue(unicode); json = sw.ToString(); Assert.AreEqual(3, json.Length); Assert.AreEqual("\"\u5f20\"", json); } [Test] public void WriteEndOnProperty() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); writer.WriteEnd(); Assert.AreEqual("{'Blah':null}", sw.ToString()); } #if !NET20 [Test] public void QuoteChar() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatString = "yyyy gg"; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteValue(new byte[] { 1, 2, 3 }); writer.WriteValue(TimeSpan.Zero); writer.WriteValue(new Uri("http://www.google.com/")); writer.WriteValue(Guid.Empty); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000-01-01T01:01:01Z', '2000-01-01T01:01:01+00:00', '\/Date(946688461000)\/', '\/Date(946688461000+0000)\/', '2000 A.D.', '2000 A.D.', 'AQID', '00:00:00', 'http://www.google.com/', '00000000-0000-0000-0000-000000000000' ]", sw.ToString()); } [Test] [Ignore("Some PC get AM than a.m.")] public void Culture() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.DateFormatString = "yyyy tt"; writer.Culture = new CultureInfo("en-NZ"); writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteEnd(); StringAssert.AreEqual(@"[ '2000 a.m.', '2000 a.m.' ]", sw.ToString()); } #endif [Test] public void CompareNewStringEscapingWithOld() { char c = (char)0; do { StringWriter swNew = new StringWriter(); char[] buffer = null; JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, ref buffer); StringWriter swOld = new StringWriter(); WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true); string newText = swNew.ToString(); string oldText = swOld.ToString(); if (newText != oldText) throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int)c, oldText, newText)); c++; } while (c != char.MaxValue); } private const string EscapedUnicodeText = "!"; private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters) { // leading delimiter if (appendDelimiters) writer.Write(delimiter); if (s != null) { char[] chars = null; char[] unicodeBuffer = null; int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\' && c != delimiter) continue; string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; case '\'': // this charater is being used as the delimiter escapedValue = @"\'"; break; case '"': // this charater is being used as the delimiter escapedValue = "\\\""; break; default: if (c <= '\u001f') { if (unicodeBuffer == null) unicodeBuffer = new char[6]; StringUtils.ToCharAsUnicode(c, unicodeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } else { escapedValue = null; } break; } if (escapedValue == null) continue; if (i > lastWritePosition) { if (chars == null) chars = s.ToCharArray(); // write unchanged chars before writing escaped text writer.Write(chars, lastWritePosition, i - lastWritePosition); } lastWritePosition = i + 1; if (!string.Equals(escapedValue, EscapedUnicodeText)) writer.Write(escapedValue); else writer.Write(unicodeBuffer); } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { if (chars == null) chars = s.ToCharArray(); // write remaining text writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); } } // trailing delimiter if (appendDelimiters) writer.Write(delimiter); } [Test] public void CustomJsonTextWriterTests() { StringWriter sw = new StringWriter(); CustomJsonTextWriter writer = new CustomJsonTextWriter(sw) { Formatting = Formatting.Indented }; writer.WriteStartObject(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WritePropertyName("Property1"); Assert.AreEqual(WriteState.Property, writer.WriteState); Assert.AreEqual("Property1", writer.Path); writer.WriteNull(); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WriteEndObject(); Assert.AreEqual(WriteState.Start, writer.WriteState); StringAssert.AreEqual(@"{{{ ""1ytreporP"": NULL!!! }}}", sw.ToString()); } [Test] public void QuoteDictionaryNames() { var d = new Dictionary<string, int> { { "a", 1 }, }; var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, }; var serializer = JsonSerializer.Create(jsonSerializerSettings); using (var stringWriter = new StringWriter()) { using (var writer = new JsonTextWriter(stringWriter) { QuoteName = false }) { serializer.Serialize(writer, d); writer.Close(); } StringAssert.AreEqual(@"{ a: 1 }", stringWriter.ToString()); } } [Test] public void WriteComments() { string json = @"//comment*//*hi*/ {//comment Name://comment true//comment after true" + StringUtils.CarriageReturn + @" ,//comment after comma" + StringUtils.CarriageReturnLineFeed + @" ""ExpiryDate""://comment" + StringUtils.LineFeed + @" new " + StringUtils.LineFeed + @"Constructor (//comment null//comment ), ""Price"": 3.99, ""Sizes"": //comment [//comment ""Small""//comment ]//comment }//comment //comment 1 "; JsonTextReader r = new JsonTextReader(new StringReader(json)); StringWriter sw = new StringWriter(); JsonTextWriter w = new JsonTextWriter(sw); w.Formatting = Formatting.Indented; w.WriteToken(r, true); StringAssert.AreEqual(@"/*comment*//*hi*/*/{/*comment*/ ""Name"": /*comment*/ true/*comment after true*//*comment after comma*/, ""ExpiryDate"": /*comment*/ new Constructor( /*comment*/, null /*comment*/ ), ""Price"": 3.99, ""Sizes"": /*comment*/ [ /*comment*/ ""Small"" /*comment*/ ]/*comment*/ }/*comment *//*comment 1 */", sw.ToString()); } } public class CustomJsonTextWriter : JsonTextWriter { private readonly TextWriter _writer; public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter) { _writer = textWriter; } public override void WritePropertyName(string name) { WritePropertyName(name, true); } public override void WritePropertyName(string name, bool escape) { SetWriteState(JsonToken.PropertyName, name); if (QuoteName) _writer.Write(QuoteChar); _writer.Write(new string(name.ToCharArray().Reverse().ToArray())); if (QuoteName) _writer.Write(QuoteChar); _writer.Write(':'); } public override void WriteNull() { SetWriteState(JsonToken.Null, null); _writer.Write("NULL!!!"); } public override void WriteStartObject() { SetWriteState(JsonToken.StartObject, null); _writer.Write("{{{"); } public override void WriteEndObject() { SetWriteState(JsonToken.EndObject, null); } protected override void WriteEnd(JsonToken token) { if (token == JsonToken.EndObject) _writer.Write("}}}"); else base.WriteEnd(token); } } #if !(PORTABLE || NETFX_CORE) public struct ConvertibleInt : IConvertible { private readonly int _value; public ConvertibleInt(int value) { _value = value; } public TypeCode GetTypeCode() { return TypeCode.Int32; } public bool ToBoolean(IFormatProvider provider) { throw new NotImplementedException(); } public byte ToByte(IFormatProvider provider) { throw new NotImplementedException(); } public char ToChar(IFormatProvider provider) { throw new NotImplementedException(); } public DateTime ToDateTime(IFormatProvider provider) { throw new NotImplementedException(); } public decimal ToDecimal(IFormatProvider provider) { throw new NotImplementedException(); } public double ToDouble(IFormatProvider provider) { throw new NotImplementedException(); } public short ToInt16(IFormatProvider provider) { throw new NotImplementedException(); } public int ToInt32(IFormatProvider provider) { throw new NotImplementedException(); } public long ToInt64(IFormatProvider provider) { throw new NotImplementedException(); } public sbyte ToSByte(IFormatProvider provider) { throw new NotImplementedException(); } public float ToSingle(IFormatProvider provider) { throw new NotImplementedException(); } public string ToString(IFormatProvider provider) { throw new NotImplementedException(); } public object ToType(Type conversionType, IFormatProvider provider) { if (conversionType == typeof(int)) return _value; throw new Exception("Type not supported: " + conversionType.FullName); } public ushort ToUInt16(IFormatProvider provider) { throw new NotImplementedException(); } public uint ToUInt32(IFormatProvider provider) { throw new NotImplementedException(); } public ulong ToUInt64(IFormatProvider provider) { throw new NotImplementedException(); } } #endif }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Threading; using System.Text; using System.Xml; using System.Security; #if USE_REFEMIT public sealed class EnumDataContract : DataContract #else internal sealed class EnumDataContract : DataContract #endif { [Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization." + " Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")] [SecurityCritical] EnumDataContractCriticalHelper helper; [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] internal EnumDataContract() : base(new EnumDataContractCriticalHelper()) { helper = base.Helper as EnumDataContractCriticalHelper; } [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.", Safe = "Doesn't leak anything.")] [SecuritySafeCritical] internal EnumDataContract(Type type) : base(new EnumDataContractCriticalHelper(type)) { helper = base.Helper as EnumDataContractCriticalHelper; } [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up base contract name for a type.", Safe = "Read only access.")] [SecuritySafeCritical] static internal XmlQualifiedName GetBaseContractName(Type type) { return EnumDataContractCriticalHelper.GetBaseContractName(type); } [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up a base contract name.", Safe = "Read only access.")] [SecuritySafeCritical] static internal Type GetBaseType(XmlQualifiedName baseContractName) { return EnumDataContractCriticalHelper.GetBaseType(baseContractName); } internal XmlQualifiedName BaseContractName { [Fx.Tag.SecurityNote(Critical = "Fetches the critical BaseContractName property.", Safe = "BaseContractName only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.BaseContractName; } [Fx.Tag.SecurityNote(Critical = "Sets the critical BaseContractName property.")] [SecurityCritical] set { helper.BaseContractName = value; } } internal List<DataMember> Members { [Fx.Tag.SecurityNote(Critical = "Fetches the critical Members property.", Safe = "Members only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.Members; } [Fx.Tag.SecurityNote(Critical = "Sets the critical Members property.")] [SecurityCritical] set { helper.Members = value; } } internal List<long> Values { [Fx.Tag.SecurityNote(Critical = "Fetches the critical Values property.", Safe = "Values only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.Values; } [Fx.Tag.SecurityNote(Critical = "Sets the critical Values property.")] [SecurityCritical] set { helper.Values = value; } } internal bool IsFlags { [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsFlags property.", Safe = "IsFlags only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.IsFlags; } [Fx.Tag.SecurityNote(Critical = "Sets the critical IsFlags property.")] [SecurityCritical] set { helper.IsFlags = value; } } internal bool IsULong { [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsULong property.", Safe = "IsULong only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.IsULong; } } XmlDictionaryString[] ChildElementNames { [Fx.Tag.SecurityNote(Critical = "Fetches the critical ChildElementNames property.", Safe = "ChildElementNames only needs to be protected for write.")] [SecuritySafeCritical] get { return helper.ChildElementNames; } } internal override bool CanContainReferences { get { return false; } } [Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing enums." + " Since the data is cached statically, we lock down access to it.")] [SecurityCritical(SecurityCriticalScope.Everything)] class EnumDataContractCriticalHelper : DataContract.DataContractCriticalHelper { static Dictionary<Type, XmlQualifiedName> typeToName; static Dictionary<XmlQualifiedName, Type> nameToType; XmlQualifiedName baseContractName; List<DataMember> members; List<long> values; bool isULong; bool isFlags; bool hasDataContract; XmlDictionaryString[] childElementNames; static EnumDataContractCriticalHelper() { typeToName = new Dictionary<Type, XmlQualifiedName>(); nameToType = new Dictionary<XmlQualifiedName, Type>(); Add(typeof(sbyte), "byte"); Add(typeof(byte), "unsignedByte"); Add(typeof(short), "short"); Add(typeof(ushort), "unsignedShort"); Add(typeof(int), "int"); Add(typeof(uint), "unsignedInt"); Add(typeof(long), "long"); Add(typeof(ulong), "unsignedLong"); } [SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "typeToName", Justification = "No need to support type equivalence here.")] static internal void Add(Type type, string localName) { XmlQualifiedName stableName = CreateQualifiedName(localName, Globals.SchemaNamespace); typeToName.Add(type, stableName); nameToType.Add(stableName, type); } static internal XmlQualifiedName GetBaseContractName(Type type) { XmlQualifiedName retVal = null; typeToName.TryGetValue(type, out retVal); return retVal; } static internal Type GetBaseType(XmlQualifiedName baseContractName) { Type retVal = null; nameToType.TryGetValue(baseContractName, out retVal); return retVal; } internal EnumDataContractCriticalHelper() { IsValueType = true; } internal EnumDataContractCriticalHelper(Type type) : base(type) { this.StableName = DataContract.GetStableName(type, out hasDataContract); Type baseType = Enum.GetUnderlyingType(type); baseContractName = GetBaseContractName(baseType); ImportBaseType(baseType); IsFlags = type.IsDefined(Globals.TypeOfFlagsAttribute, false); ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(2 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = dictionary.Add(StableName.Namespace); childElementNames = new XmlDictionaryString[Members.Count]; for (int i = 0; i < Members.Count; i++) childElementNames[i] = dictionary.Add(Members[i].Name); DataContractAttribute dataContractAttribute; if (TryGetDCAttribute(type, out dataContractAttribute)) { if (dataContractAttribute.IsReference) { DataContract.ThrowInvalidDataContractException( SR.GetString(SR.EnumTypeCannotHaveIsReference, DataContract.GetClrTypeFullName(type), dataContractAttribute.IsReference, false), type); } } } internal XmlQualifiedName BaseContractName { get { return baseContractName; } set { baseContractName = value; Type baseType = GetBaseType(baseContractName); if (baseType == null) ThrowInvalidDataContractException(SR.GetString(SR.InvalidEnumBaseType, value.Name, value.Namespace, StableName.Name, StableName.Namespace)); ImportBaseType(baseType); } } internal List<DataMember> Members { get { return members; } set { members = value; } } internal List<long> Values { get { return values; } set { values = value; } } internal bool IsFlags { get { return isFlags; } set { isFlags = value; } } internal bool IsULong { get { return isULong; } } internal XmlDictionaryString[] ChildElementNames { get { return childElementNames; } } void ImportBaseType(Type baseType) { isULong = (baseType == Globals.TypeOfULong); } void ImportDataMembers() { Type type = this.UnderlyingType; FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public); Dictionary<string, DataMember> memberValuesTable = new Dictionary<string, DataMember>(); List<DataMember> tempMembers = new List<DataMember>(fields.Length); List<long> tempValues = new List<long>(fields.Length); for (int i = 0; i < fields.Length; i++) { FieldInfo field = fields[i]; bool enumMemberValid = false; if (hasDataContract) { object[] memberAttributes = field.GetCustomAttributes(Globals.TypeOfEnumMemberAttribute, false); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.GetString(SR.TooManyEnumMembers, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name)); EnumMemberAttribute memberAttribute = (EnumMemberAttribute)memberAttributes[0]; DataMember memberContract = new DataMember(field); if (memberAttribute.IsValueSetExplicit) { if (memberAttribute.Value == null || memberAttribute.Value.Length == 0) ThrowInvalidDataContractException(SR.GetString(SR.InvalidEnumMemberValue, field.Name, DataContract.GetClrTypeFullName(type))); memberContract.Name = memberAttribute.Value; } else memberContract.Name = field.Name; ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable); enumMemberValid = true; } object[] dataMemberAttributes = field.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, false); if (dataMemberAttributes != null && dataMemberAttributes.Length > 0) ThrowInvalidDataContractException(SR.GetString(SR.DataMemberOnEnumField, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name)); } else { if (!field.IsNotSerialized) { DataMember memberContract = new DataMember(field); memberContract.Name = field.Name; ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable); enumMemberValid = true; } } if (enumMemberValid) { object enumValue = field.GetValue(null); if (isULong) tempValues.Add((long)((IConvertible)enumValue).ToUInt64(null)); else tempValues.Add(((IConvertible)enumValue).ToInt64(null)); } } Thread.MemoryBarrier(); members = tempMembers; values = tempValues; } } internal void WriteEnumValue(XmlWriterDelegator writer, object value) { long longValue = IsULong ? (long)((IConvertible)value).ToUInt64(null) : ((IConvertible)value).ToInt64(null); for (int i = 0; i < Values.Count; i++) { if (longValue == Values[i]) { writer.WriteString(ChildElementNames[i].Value); return; } } if (IsFlags) { int zeroIndex = -1; bool noneWritten = true; for (int i = 0; i < Values.Count; i++) { long current = Values[i]; if (current == 0) { zeroIndex = i; continue; } if (longValue == 0) break; if ((current & longValue) == current) { if (noneWritten) noneWritten = false; else writer.WriteString(DictionaryGlobals.Space.Value); writer.WriteString(ChildElementNames[i].Value); longValue &= ~current; } } // enforce that enum value was completely parsed if (longValue != 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType)))); if (noneWritten && zeroIndex >= 0) writer.WriteString(ChildElementNames[zeroIndex].Value); } else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType)))); } internal object ReadEnumValue(XmlReaderDelegator reader) { string stringValue = reader.ReadElementContentAsString(); long longValue = 0; int i = 0; if (IsFlags) { // Skip initial spaces for (; i < stringValue.Length; i++) if (stringValue[i] != ' ') break; // Read space-delimited values int startIndex = i; int count = 0; for (; i < stringValue.Length; i++) { if (stringValue[i] == ' ') { count = i - startIndex; if (count > 0) longValue |= ReadEnumValue(stringValue, startIndex, count); for (++i; i < stringValue.Length; i++) if (stringValue[i] != ' ') break; startIndex = i; if (i == stringValue.Length) break; } } count = i - startIndex; if (count > 0) longValue |= ReadEnumValue(stringValue, startIndex, count); } else { if (stringValue.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.InvalidEnumValueOnRead, stringValue, DataContract.GetClrTypeFullName(UnderlyingType)))); longValue = ReadEnumValue(stringValue, 0, stringValue.Length); } if (IsULong) return Enum.ToObject(UnderlyingType, (ulong)longValue); return Enum.ToObject(UnderlyingType, longValue); } long ReadEnumValue(string value, int index, int count) { for (int i = 0; i < Members.Count; i++) { string memberName = Members[i].Name; if (memberName.Length == count && String.CompareOrdinal(value, index, memberName, 0, count) == 0) { return Values[i]; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.InvalidEnumValueOnRead, value.Substring(index, count), DataContract.GetClrTypeFullName(UnderlyingType)))); } internal string GetStringFromEnumValue(long value) { if (IsULong) return XmlConvert.ToString((ulong)value); else return XmlConvert.ToString(value); } internal long GetEnumValueFromString(string value) { if (IsULong) return (long)XmlConverter.ToUInt64(value); else return XmlConverter.ToInt64(value); } internal override bool Equals(object other, Dictionary<DataContractPairKey, object> checkedContracts) { if (IsEqualOrChecked(other, checkedContracts)) return true; if (base.Equals(other, null)) { EnumDataContract dataContract = other as EnumDataContract; if (dataContract != null) { if (Members.Count != dataContract.Members.Count || Values.Count != dataContract.Values.Count) return false; string[] memberNames1 = new string[Members.Count], memberNames2 = new string[Members.Count]; for (int i = 0; i < Members.Count; i++) { memberNames1[i] = Members[i].Name; memberNames2[i] = dataContract.Members[i].Name; } Array.Sort(memberNames1); Array.Sort(memberNames2); for (int i = 0; i < Members.Count; i++) { if (memberNames1[i] != memberNames2[i]) return false; } return (IsFlags == dataContract.IsFlags); } } return false; } public override int GetHashCode() { return base.GetHashCode(); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { WriteEnumValue(xmlWriter, obj); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { object obj = ReadEnumValue(xmlReader); if (context != null) context.AddNewObject(obj); return obj; } } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Result = com.google.zxing.Result; namespace com.google.zxing.client.result { /// <summary> <p>Abstract class representing the result of decoding a barcode, as more than /// a String -- as some type of structured data. This might be a subclass which represents /// a URL, or an e-mail address. {@link #parseResult(com.google.zxing.Result)} will turn a raw /// decoded string into the most appropriate type of structured representation.</p> /// /// <p>Thanks to Jeff Griffin for proposing rewrite of these classes that relies less /// on exception-based mechanisms during parsing.</p> /// /// </summary> /// <author> Sean Owen /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> public abstract class ResultParser { public static ParsedResult parseResult(Result theResult) { // Simplification of original if - if else logic using Null Coalescing operator ?? // // ?? Simply checks from left to right for a non null object // when an object evaluates to null the next object after the ?? is evaluated // This continues until a non null value is found or the last object is evaluated return BookmarkDoCoMoResultParser.parse(theResult) as ParsedResult ?? AddressBookDoCoMoResultParser.parse(theResult) as ParsedResult ?? EmailDoCoMoResultParser.parse(theResult) as ParsedResult ?? AddressBookAUResultParser.parse(theResult) as ParsedResult ?? VCardResultParser.parse(theResult) as ParsedResult ?? BizcardResultParser.parse(theResult) as ParsedResult ?? VEventResultParser.parse(theResult) as ParsedResult ?? EmailAddressResultParser.parse(theResult) as ParsedResult ?? TelResultParser.parse(theResult) as ParsedResult ?? SMSMMSResultParser.parse(theResult) as ParsedResult ?? GeoResultParser.parse(theResult) as ParsedResult ?? URLTOResultParser.parse(theResult) as ParsedResult ?? URIResultParser.parse(theResult) as ParsedResult ?? ISBNResultParser.parse(theResult) as ParsedResult ?? ProductResultParser.parse(theResult) as ParsedResult ?? new TextParsedResult(theResult.Text, null) as ParsedResult; } protected internal static void maybeAppend(System.String value_Renamed, System.Text.StringBuilder result) { if (value_Renamed != null) { result.Append('\n'); result.Append(value_Renamed); } } protected internal static void maybeAppend(System.String[] value_Renamed, System.Text.StringBuilder result) { if (value_Renamed != null) { for (int i = 0; i < value_Renamed.Length; i++) { result.Append('\n'); result.Append(value_Renamed[i]); } } } protected internal static System.String[] maybeWrap(System.String value_Renamed) { return value_Renamed == null ? null : new System.String[] { value_Renamed }; } protected internal static System.String unescapeBackslash(System.String escaped) { if (escaped != null) { int backslash = escaped.IndexOf('\\'); if (backslash >= 0) { int max = escaped.Length; System.Text.StringBuilder unescaped = new System.Text.StringBuilder(max - 1); unescaped.Append(escaped.ToCharArray(), 0, backslash); bool nextIsEscaped = false; for (int i = backslash; i < max; i++) { char c = escaped[i]; if (nextIsEscaped || c != '\\') { unescaped.Append(c); nextIsEscaped = false; } else { nextIsEscaped = true; } } return unescaped.ToString(); } } return escaped; } private static System.String urlDecode(System.String escaped) { // No we can't use java.net.URLDecoder here. JavaME doesn't have it. if (escaped == null) { return null; } char[] escapedArray = escaped.ToCharArray(); int first = findFirstEscape(escapedArray); if (first < 0) { return escaped; } int max = escapedArray.Length; // final length is at most 2 less than original due to at least 1 unescaping System.Text.StringBuilder unescaped = new System.Text.StringBuilder(max - 2); // Can append everything up to first escape character unescaped.Append(escapedArray, 0, first); for (int i = first; i < max; i++) { char c = escapedArray[i]; if (c == '+') { // + is translated directly into a space unescaped.Append(' '); } else if (c == '%') { // Are there even two more chars? if not we will just copy the escaped sequence and be done if (i >= max - 2) { unescaped.Append('%'); // append that % and move on } else { int firstDigitValue = parseHexDigit(escapedArray[++i]); int secondDigitValue = parseHexDigit(escapedArray[++i]); if (firstDigitValue < 0 || secondDigitValue < 0) { // bad digit, just move on unescaped.Append('%'); unescaped.Append(escapedArray[i - 1]); unescaped.Append(escapedArray[i]); } unescaped.Append((char)((firstDigitValue << 4) + secondDigitValue)); } } else { unescaped.Append(c); } } return unescaped.ToString(); } private static int findFirstEscape(char[] escapedArray) { int max = escapedArray.Length; for (int i = 0; i < max; i++) { char c = escapedArray[i]; if (c == '+' || c == '%') { return i; } } return -1; } private static int parseHexDigit(char c) { if (c >= 'a') { if (c <= 'f') { return 10 + (c - 'a'); } } else if (c >= 'A') { if (c <= 'F') { return 10 + (c - 'A'); } } else if (c >= '0') { if (c <= '9') { return c - '0'; } } return -1; } protected internal static bool isStringOfDigits(System.String value_Renamed, int length) { if (value_Renamed == null) { return false; } int stringLength = value_Renamed.Length; if (length != stringLength) { return false; } for (int i = 0; i < length; i++) { char c = value_Renamed[i]; if (c < '0' || c > '9') { return false; } } return true; } protected internal static bool isSubstringOfDigits(System.String value_Renamed, int offset, int length) { if (value_Renamed == null) { return false; } int stringLength = value_Renamed.Length; int max = offset + length; if (stringLength < max) { return false; } for (int i = offset; i < max; i++) { char c = value_Renamed[i]; if (c < '0' || c > '9') { return false; } } return true; } internal static Dictionary<object, object> parseNameValuePairs(System.String uri) { int paramStart = uri.IndexOf('?'); if (paramStart < 0) { return null; } Dictionary<object, object> result = new Dictionary<object, object>(); paramStart++; int paramEnd; //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" while ((paramEnd = uri.IndexOf('&', paramStart)) >= 0) { appendKeyValue(uri, paramStart, paramEnd, result); paramStart = paramEnd + 1; } appendKeyValue(uri, paramStart, uri.Length, result); return result; } private static void appendKeyValue(System.String uri, int paramStart, int paramEnd, Dictionary<object, object> result) { //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" int separator = uri.IndexOf('=', paramStart); if (separator >= 0) { // key = value System.String key = uri.Substring(paramStart, (separator) - (paramStart)); System.String value_Renamed = uri.Substring(separator + 1, (paramEnd) - (separator + 1)); value_Renamed = urlDecode(value_Renamed); result[key] = value_Renamed; } // Can't put key, null into a hashtable } internal static System.String[] matchPrefixedField(System.String prefix, System.String rawText, char endChar, bool trim) { List<object> matches = null; int i = 0; int max = rawText.Length; while (i < max) { //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" i = rawText.IndexOf(prefix, i); if (i < 0) { break; } i += prefix.Length; // Skip past this prefix we found to start int start = i; // Found the start of a match here bool done = false; while (!done) { //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" i = rawText.IndexOf((System.Char)endChar, i); if (i < 0) { // No terminating end character? uh, done. Set i such that loop terminates and break i = rawText.Length; done = true; } else if (rawText[i - 1] == '\\') { // semicolon was escaped so continue i++; } else { // found a match if (matches == null) { matches = new List<object>(); } System.String element = unescapeBackslash(rawText.Substring(start, (i) - (start))); if (trim) { element = element.Trim(); } matches.Add(element); i++; done = true; } } } if (matches == null || (matches.Count == 0)) { return null; } return toStringArray(matches); } internal static System.String matchSinglePrefixedField(System.String prefix, System.String rawText, char endChar, bool trim) { System.String[] matches = matchPrefixedField(prefix, rawText, endChar, trim); return matches == null ? null : matches[0]; } internal static System.String[] toStringArray(List<object> strings) { int size = strings.Count; System.String[] result = new System.String[size]; for (int j = 0; j < size; j++) { result[j] = ((System.String)strings[j]); } return result; } } }
using System; using CSF.Screenplay.Abilities; using CSF.Screenplay.Actors; using CSF.Screenplay.Performables; using CSF.Screenplay.Reporting; namespace CSF.Screenplay.Actors { /// <summary> /// The main implementation of <see cref="IActor"/>. which represents an actor/participant/persona within a test /// scenario. /// </summary> /// <remarks> /// <para> /// Actors may be given abilities, which provide the actions which they can take. /// In order to have them use those abilities to perform actions, you should use the static members of /// <see cref="StepComposer"/>. It is recommended to use these via a <c>using static CSF.Screenplay.StepComposer;</c> /// statement. This permits usages such as: /// </para> /// <code> /// Given(joe).WasAbleTo(takeOutTheTrash); /// </code> /// </remarks> public class Actor : IActor { #region fields readonly IAbilityStore abilityStore; readonly string name; readonly Guid scenarioIdentity; #endregion #region properties /// <summary> /// Gets the name of the current actor. /// </summary> /// <value>The name.</value> public virtual string Name => name; /// <summary> /// Gets the identity of the scenario with which the current actor is associated. /// </summary> /// <value>The scenario identity.</value> public virtual Guid ScenarioIdentity => scenarioIdentity; #endregion #region methods /// <summary> /// Adds an ability of the indicated type to the current instance. /// </summary> /// <remarks> /// <para> /// This overload requires that the ability type has a public parameterless constructor. /// An instance of the ability type is created/instantiated as part of this operation. /// </para> /// </remarks> /// <typeparam name="TAbility">The desired ability type.</typeparam> public virtual void IsAbleTo<TAbility>() where TAbility : IAbility,new() { var ability = abilityStore.Add(typeof(TAbility)); InvokeGainedAbility(ability); } /// <summary> /// Adds an ability of the indicated type to the current instance. /// </summary> /// <remarks> /// <para> /// This overload requires that the ability type has a public parameterless constructor. /// An instance of the ability type is created/instantiated as part of this operation. /// </para> /// </remarks> /// <param name="abilityType">The desired ability type.</param> public virtual void IsAbleTo(Type abilityType) { var ability = abilityStore.Add(abilityType); InvokeGainedAbility(ability); } /// <summary> /// Adds an ability object to the current instance. /// </summary> /// <param name="ability">The ability.</param> public virtual void IsAbleTo(IAbility ability) { abilityStore.Add(ability); InvokeGainedAbility(ability); } /// <summary> /// Performs an action or task. /// </summary> /// <param name="performable">The performable item to execute.</param> protected virtual void Perform(IPerformable performable) { if(ReferenceEquals(performable, null)) throw new ArgumentNullException(nameof(performable)); try { InvokeBeginPerformance(performable); performable.PerformAs(this); InvokeEndPerformance(performable); } catch(Exception ex) { InvokePerformanceFailed(performable, ex); throw; } } /// <summary> /// Performs an action or task which has a public parameterless constructor. /// </summary> /// <typeparam name="TPerformable">The type of the performable item to execute.</typeparam> protected virtual void Perform<TPerformable>() where TPerformable : IPerformable,new() { var performable = Activator.CreateInstance<TPerformable>(); Perform(performable); } /// <summary> /// Performs an action, task or asks a question which returns a result value. /// </summary> /// <returns>The result of performing the item</returns> /// <param name="performable">The performable item to execute.</param> /// <typeparam name="TResult">The result type.</typeparam> protected virtual TResult Perform<TResult>(IPerformable<TResult> performable) { if(ReferenceEquals(performable, null)) throw new ArgumentNullException(nameof(performable)); TResult result; try { InvokeBeginPerformance(performable); result = performable.PerformAs(this); InvokePerformanceResult(performable, result); InvokeEndPerformance(performable); } catch(Exception ex) { InvokePerformanceFailed(performable, ex); throw; } return result; } /// <summary> /// Determines whether or not the given performer has an ability or not. /// </summary> /// <returns><c>true</c>, if the performer has the ability, <c>false</c> otherwise.</returns> /// <typeparam name="TAbility">The desired ability type.</typeparam> protected virtual bool HasAbility<TAbility>() where TAbility : IAbility { return abilityStore.HasAbility<TAbility>(); } /// <summary> /// Gets an ability of the noted type. /// </summary> /// <returns>The ability.</returns> /// <typeparam name="TAbility">The desired ability type.</typeparam> protected virtual TAbility GetAbility<TAbility>() where TAbility : IAbility { var ability = abilityStore.GetAbility<TAbility>(); if(ReferenceEquals(ability, null)) { var message = String.Format(Resources.ExceptionFormats.ActorIsMissingAnAbility, Name, typeof(TAbility).Name); throw new MissingAbilityException(message); } return ability; } #endregion #region events and invokers /// <summary> /// Occurs when the actor begins a performance. /// </summary> public event EventHandler<BeginPerformanceEventArgs> BeginPerformance; /// <summary> /// Occurs when an actor ends a performance. /// </summary> public event EventHandler<EndSuccessfulPerformanceEventArgs> EndPerformance; /// <summary> /// Occurs when an actor receives a result from a performance. /// </summary> public event EventHandler<PerformanceResultEventArgs> PerformanceResult; /// <summary> /// Occurs when a performance fails with an exception. /// </summary> public event EventHandler<PerformanceFailureEventArgs> PerformanceFailed; /// <summary> /// Occurs when an actor gains a new ability. /// </summary> public event EventHandler<GainAbilityEventArgs> GainedAbility; /// <summary> /// Occurs when the actor begins a 'Given' task, action or question. /// </summary> public event EventHandler<ActorEventArgs> BeginGiven; /// <summary> /// Occurs when the actor finishes a 'Given' task, action or question. /// </summary> public event EventHandler<ActorEventArgs> EndGiven; /// <summary> /// Occurs when the actor begins a 'When' task, action or question. /// </summary> public event EventHandler<ActorEventArgs> BeginWhen; /// <summary> /// Occurs when the actor finishes a 'When' task, action or question. /// </summary> public event EventHandler<ActorEventArgs> EndWhen; /// <summary> /// Occurs when the actor begins a 'Then' task, action or question (usually a question). /// </summary> public event EventHandler<ActorEventArgs> BeginThen; /// <summary> /// Occurs when the actor finishes a 'Then' task, action or question (usually a question). /// </summary> public event EventHandler<ActorEventArgs> EndThen; /// <summary> /// Invokes the begin performance event. /// </summary> /// <param name="performable">Performable.</param> protected virtual void InvokeBeginPerformance(IPerformable performable) { var args = new BeginPerformanceEventArgs(this, performable); BeginPerformance?.Invoke(this, args); } /// <summary> /// Invokes the end performance event. /// </summary> /// <param name="performable">Performable.</param> protected virtual void InvokeEndPerformance(IPerformable performable) { var args = new EndSuccessfulPerformanceEventArgs(this, performable); EndPerformance?.Invoke(this, args); } /// <summary> /// Invokes the performance result event. /// </summary> /// <param name="performable">Performable.</param> /// <param name="result">Result.</param> protected virtual void InvokePerformanceResult(IPerformable performable, object result) { var args = new PerformanceResultEventArgs(this, performable, result); PerformanceResult?.Invoke(this, args); } /// <summary> /// Invokes the performance failed event. /// </summary> /// <param name="performable">Performable.</param> /// <param name="exception">Exception.</param> protected virtual void InvokePerformanceFailed(IPerformable performable, Exception exception) { var args = new PerformanceFailureEventArgs(this, performable, exception); PerformanceFailed?.Invoke(this, args); } /// <summary> /// Invokes the gained ability event. /// </summary> /// <param name="ability">Ability.</param> protected virtual void InvokeGainedAbility(IAbility ability) { var args = new GainAbilityEventArgs(this, ability); GainedAbility?.Invoke(this, args); } /// <summary> /// Invokes the begin-given event. /// </summary> protected virtual void InvokeBeginGiven() { var args = new ActorEventArgs(this); BeginGiven?.Invoke(this, args); } /// <summary> /// Invokes the end-given event. /// </summary> protected virtual void InvokeEndGiven() { var args = new ActorEventArgs(this); EndGiven?.Invoke(this, args); } /// <summary> /// Invokes the begin-when event. /// </summary> protected virtual void InvokeBeginWhen() { var args = new ActorEventArgs(this); BeginWhen?.Invoke(this, args); } /// <summary> /// Invokes the end-when event. /// </summary> protected virtual void InvokeEndWhen() { var args = new ActorEventArgs(this); EndWhen?.Invoke(this, args); } /// <summary> /// Invokes the begin-then event. /// </summary> protected virtual void InvokeBeginThen() { var args = new ActorEventArgs(this); BeginThen?.Invoke(this, args); } /// <summary> /// Invokes the end-then event. /// </summary> protected virtual void InvokeEndThen() { var args = new ActorEventArgs(this); EndThen?.Invoke(this, args); } #endregion #region explicit IPerformer and IActor implementations void IGivenActor.WasAbleTo(IPerformable performable) { InvokeBeginGiven(); Perform(performable); InvokeEndGiven(); } void IGivenActor.WasAbleTo<TPerformable>() { InvokeBeginGiven(); Perform<TPerformable>(); InvokeEndGiven(); } void IWhenActor.AttemptsTo(IPerformable performable) { InvokeBeginWhen(); Perform(performable); InvokeEndWhen(); } void IWhenActor.AttemptsTo<TPerformable>() { InvokeBeginWhen(); Perform<TPerformable>(); InvokeEndWhen(); } void IThenActor.Should(IPerformable performable) { InvokeBeginThen(); Perform(performable); InvokeEndThen(); } void IThenActor.Should<TPerformable>() { InvokeBeginThen(); Perform<TPerformable>(); InvokeEndThen(); } TResult IGivenActor.WasAbleTo<TResult>(IPerformable<TResult> performable) { InvokeBeginGiven(); var result = Perform(performable); InvokeEndGiven(); return result; } TResult IWhenActor.AttemptsTo<TResult>(IPerformable<TResult> performable) { InvokeBeginWhen(); var result = Perform(performable); InvokeEndWhen(); return result; } TResult IThenActor.Should<TResult>(IPerformable<TResult> performable) { InvokeBeginThen(); var result = Perform(performable); InvokeEndThen(); return result; } TResult Got<TResult>(IQuestion<TResult> question) { InvokeBeginGiven(); var result = Perform(question); InvokeEndGiven(); return result; } TResult Gets<TResult>(IQuestion<TResult> question) { InvokeBeginWhen(); var result = Perform(question); InvokeEndWhen(); return result; } TResult ShouldGet<TResult>(IQuestion<TResult> question) { InvokeBeginThen(); var result = Perform(question); InvokeEndThen(); return result; } TResult IGivenActor.Saw<TResult>(IQuestion<TResult> question) => Got(question); TResult IGivenActor.Got<TResult>(IQuestion<TResult> question) => Got(question); TResult IGivenActor.Read<TResult>(IQuestion<TResult> question) => Got(question); TResult IWhenActor.Sees<TResult>(IQuestion<TResult> question) => Gets(question); TResult IWhenActor.Gets<TResult>(IQuestion<TResult> question) => Gets(question); TResult IWhenActor.Reads<TResult>(IQuestion<TResult> question) => Gets(question); TResult IThenActor.ShouldSee<TResult>(IQuestion<TResult> question) => ShouldGet(question); TResult IThenActor.ShouldGet<TResult>(IQuestion<TResult> question) => ShouldGet(question); TResult IThenActor.ShouldRead<TResult>(IQuestion<TResult> question) => ShouldGet(question); bool IPerformer.HasAbility<TAbility>() { return HasAbility<TAbility>(); } TAbility IPerformer.GetAbility<TAbility>() { return GetAbility<TAbility>(); } void IPerformer.Perform(IPerformable performable) { Perform(performable); } void IPerformer.Perform<TPerformable>() { Perform<TPerformable>(); } TResult IPerformer.Perform<TResult>(IPerformable<TResult> performable) { return Perform(performable); } #endregion #region constructor /// <summary> /// Initializes a new instance of the <see cref="Actor"/> class. /// </summary> /// <param name="name">The actor's name.</param> /// <param name="scenarioIdentity">The screenplay scenario identity.</param> public Actor(string name, Guid scenarioIdentity) { if(name == null) throw new ArgumentNullException(nameof(name)); if(scenarioIdentity == Guid.Empty) throw new ArgumentException(Resources.ExceptionFormats.ActorMustHaveAScenarioId, nameof(scenarioIdentity)); this.name = name; this.scenarioIdentity = scenarioIdentity; abilityStore = new AbilityStore(); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace JoinProto.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Diagnostics; using System.Text; using u8 = System.Byte; namespace System.Data.SQLite { internal partial class Sqlite3 { /* ** 2006 June 10 ** ** 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 code used to help implement virtual tables. ************************************************************************* ** 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: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ #if !SQLITE_OMIT_VIRTUALTABLE //#include "sqliteInt.h" /* ** Before a virtual table xCreate() or xConnect() method is invoked, the ** sqlite3.pVtabCtx member variable is set to point to an instance of ** this struct allocated on the stack. It is used by the implementation of ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which ** are invoked only from within xCreate and xConnect methods. */ public class VtabCtx { public Table pTab; public VTable pVTable; }; /* ** The actual function that does the work of creating a new module. ** This function implements the sqlite3_create_module() and ** sqlite3_create_module_v2() interfaces. */ static int createModule( sqlite3 db, /* Database in which module is registered */ string zName, /* Name assigned to this module */ sqlite3_module pModule, /* The definition of the module */ object pAux, /* Context pointer for xCreate/xConnect */ smdxDestroy xDestroy /* Module destructor function */ ) { int rc, nName; Module pMod; sqlite3_mutex_enter(db.mutex); nName = sqlite3Strlen30(zName); pMod = new Module();// (Module)sqlite3DbMallocRaw( db, sizeof( Module ) + nName + 1 ); if (pMod != null) { Module pDel; string zCopy;// = (char )(&pMod[1]); zCopy = zName;//memcpy(zCopy, zName, nName+1); pMod.zName = zCopy; pMod.pModule = pModule; pMod.pAux = pAux; pMod.xDestroy = xDestroy; pDel = (Module)sqlite3HashInsert(ref db.aModule, zCopy, nName, pMod); if (pDel != null && pDel.xDestroy != null) { sqlite3ResetInternalSchema(db, -1); pDel.xDestroy(ref pDel.pAux); } sqlite3DbFree(db, ref pDel); //if( pDel==pMod ){ // db.mallocFailed = 1; //} } else if (xDestroy != null) { xDestroy(ref pAux); } rc = sqlite3ApiExit(db, SQLITE_OK); sqlite3_mutex_leave(db.mutex); return rc; } /* ** External API function used to create a new virtual-table module. */ static int sqlite3_create_module( sqlite3 db, /* Database in which module is registered */ string zName, /* Name assigned to this module */ sqlite3_module pModule, /* The definition of the module */ object pAux /* Context pointer for xCreate/xConnect */ ) { return createModule(db, zName, pModule, pAux, null); } /* ** External API function used to create a new virtual-table module. */ static int sqlite3_create_module_v2( sqlite3 db, /* Database in which module is registered */ string zName, /* Name assigned to this module */ sqlite3_module pModule, /* The definition of the module */ sqlite3_vtab pAux, /* Context pointer for xCreate/xConnect */ smdxDestroy xDestroy /* Module destructor function */ ) { return createModule(db, zName, pModule, pAux, xDestroy); } /* ** Lock the virtual table so that it cannot be disconnected. ** Locks nest. Every lock should have a corresponding unlock. ** If an unlock is omitted, resources leaks will occur. ** ** If a disconnect is attempted while a virtual table is locked, ** the disconnect is deferred until all locks have been removed. */ static void sqlite3VtabLock(VTable pVTab) { pVTab.nRef++; } /* ** pTab is a pointer to a Table structure representing a virtual-table. ** Return a pointer to the VTable object used by connection db to access ** this virtual-table, if one has been created, or NULL otherwise. */ static VTable sqlite3GetVTable(sqlite3 db, Table pTab) { VTable pVtab; Debug.Assert(IsVirtual(pTab)); for (pVtab = pTab.pVTable; pVtab != null && pVtab.db != db; pVtab = pVtab.pNext) ; return pVtab; } /* ** Decrement the ref-count on a virtual table object. When the ref-count ** reaches zero, call the xDisconnect() method to delete the object. */ static void sqlite3VtabUnlock(VTable pVTab) { sqlite3 db = pVTab.db; Debug.Assert(db != null); Debug.Assert(pVTab.nRef > 0); Debug.Assert(sqlite3SafetyCheckOk(db)); pVTab.nRef--; if (pVTab.nRef == 0) { object p = pVTab.pVtab; if (p != null) { ((sqlite3_vtab)p).pModule.xDisconnect(ref p); } sqlite3DbFree(db, ref pVTab); } } /* ** Table p is a virtual table. This function moves all elements in the ** p.pVTable list to the sqlite3.pDisconnect lists of their associated ** database connections to be disconnected at the next opportunity. ** Except, if argument db is not NULL, then the entry associated with ** connection db is left in the p.pVTable list. */ static VTable vtabDisconnectAll(sqlite3 db, Table p) { VTable pRet = null; VTable pVTable = p.pVTable; p.pVTable = null; /* Assert that the mutex (if any) associated with the BtShared database ** that contains table p is held by the caller. See header comments ** above function sqlite3VtabUnlockList() for an explanation of why ** this makes it safe to access the sqlite3.pDisconnect list of any ** database connection that may have an entry in the p.pVTable list. */ Debug.Assert(db == null || sqlite3SchemaMutexHeld(db, 0, p.pSchema)); while (pVTable != null) { sqlite3 db2 = pVTable.db; VTable pNext = pVTable.pNext; Debug.Assert(db2 != null); if (db2 == db) { pRet = pVTable; p.pVTable = pRet; pRet.pNext = null; } else { pVTable.pNext = db2.pDisconnect; db2.pDisconnect = pVTable; } pVTable = pNext; } Debug.Assert(null == db || pRet != null); return pRet; } /* ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list. ** ** This function may only be called when the mutexes associated with all ** shared b-tree databases opened using connection db are held by the ** caller. This is done to protect the sqlite3.pDisconnect list. The ** sqlite3.pDisconnect list is accessed only as follows: ** ** 1) By this function. In this case, all BtShared mutexes and the mutex ** associated with the database handle itself must be held. ** ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to ** the sqlite3.pDisconnect list. In this case either the BtShared mutex ** associated with the database the virtual table is stored in is held ** or, if the virtual table is stored in a non-sharable database, then ** the database handle mutex is held. ** ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously ** by multiple threads. It is thread-safe. */ static void sqlite3VtabUnlockList(sqlite3 db) { VTable p = db.pDisconnect; db.pDisconnect = null; Debug.Assert(sqlite3BtreeHoldsAllMutexes(db)); Debug.Assert(sqlite3_mutex_held(db.mutex)); if (p != null) { sqlite3ExpirePreparedStatements(db); do { VTable pNext = p.pNext; sqlite3VtabUnlock(p); p = pNext; } while (p != null); } } /* ** Clear any and all virtual-table information from the Table record. ** This routine is called, for example, just before deleting the Table ** record. ** ** Since it is a virtual-table, the Table structure contains a pointer ** to the head of a linked list of VTable structures. Each VTable ** structure is associated with a single sqlite3* user of the schema. ** The reference count of the VTable structure associated with database ** connection db is decremented immediately (which may lead to the ** structure being xDisconnected and free). Any other VTable structures ** in the list are moved to the sqlite3.pDisconnect list of the associated ** database connection. */ static void sqlite3VtabClear(sqlite3 db, Table p) { if (null == db || db.pnBytesFreed == 0) vtabDisconnectAll(null, p); if (p.azModuleArg != null) { int i; for (i = 0; i < p.nModuleArg; i++) { sqlite3DbFree(db, ref p.azModuleArg[i]); } sqlite3DbFree(db, ref p.azModuleArg); } } /* ** Add a new module argument to pTable.azModuleArg[]. ** The string is not copied - the pointer is stored. The ** string will be freed automatically when the table is ** deleted. */ static void addModuleArgument(sqlite3 db, Table pTable, string zArg) { int i = pTable.nModuleArg++; //int nBytes = sizeof(char )*(1+pTable.nModuleArg); //string[] azModuleArg; //sqlite3DbRealloc( db, pTable.azModuleArg, nBytes ); if (pTable.azModuleArg == null || pTable.azModuleArg.Length < pTable.nModuleArg) Array.Resize(ref pTable.azModuleArg, 3 + pTable.nModuleArg); //if ( azModuleArg == null ) //{ // int j; // for ( j = 0; j < i; j++ ) // { // sqlite3DbFree( db, ref pTable.azModuleArg[j] ); // } // sqlite3DbFree( db, ref zArg ); // sqlite3DbFree( db, ref pTable.azModuleArg ); // pTable.nModuleArg = 0; //} //else { pTable.azModuleArg[i] = zArg; //pTable.azModuleArg[i + 1] = null; //azModuleArg[i+1] = 0; } //pTable.azModuleArg = azModuleArg; } /* ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE ** statement. The module name has been parsed, but the optional list ** of parameters that follow the module name are still pending. */ static void sqlite3VtabBeginParse( Parse pParse, /* Parsing context */ Token pName1, /* Name of new table, or database name */ Token pName2, /* Name of new table or NULL */ Token pModuleName /* Name of the module for the virtual table */ ) { int iDb; /* The database the table is being created in */ Table pTable; /* The new virtual table */ sqlite3 db; /* Database connection */ sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0); pTable = pParse.pNewTable; if (pTable == null) return; Debug.Assert(null == pTable.pIndex); db = pParse.db; iDb = sqlite3SchemaToIndex(db, pTable.pSchema); Debug.Assert(iDb >= 0); pTable.tabFlags |= TF_Virtual; pTable.nModuleArg = 0; addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName)); addModuleArgument(db, pTable, db.aDb[iDb].zName);//sqlite3DbStrDup( db, db.aDb[iDb].zName ) ); addModuleArgument(db, pTable, pTable.zName);//sqlite3DbStrDup( db, pTable.zName ) ); pParse.sNameToken.n = pParse.sNameToken.z.Length;// (int)[pModuleName.n] - pName1.z ); #if !SQLITE_OMIT_AUTHORIZATION /* Creating a virtual table invokes the authorization callback twice. ** The first invocation, to obtain permission to INSERT a row into the ** sqlite_master table, has already been made by sqlite3StartTable(). ** The second call, to obtain permission to create the table, is made now. */ if( pTable->azModuleArg ){ sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, pTable->azModuleArg[0], pParse->db->aDb[iDb].zName); } #endif } /* ** This routine takes the module argument that has been accumulating ** in pParse.zArg[] and appends it to the list of arguments on the ** virtual table currently under construction in pParse.pTable. */ static void addArgumentToVtab(Parse pParse) { if (pParse.sArg.z != null && ALWAYS(pParse.pNewTable)) { string z = pParse.sArg.z.Substring(0, pParse.sArg.n); int n = pParse.sArg.n; sqlite3 db = pParse.db; addModuleArgument(db, pParse.pNewTable, z);///sqlite3DbStrNDup( db, z, n ) ); } } /* ** The parser calls this routine after the CREATE VIRTUAL TABLE statement ** has been completely parsed. */ static void sqlite3VtabFinishParse(Parse pParse, Token pEnd) { Table pTab = pParse.pNewTable; /* The table being constructed */ sqlite3 db = pParse.db; /* The database connection */ if (pTab == null) return; addArgumentToVtab(pParse); pParse.sArg.z = ""; if (pTab.nModuleArg < 1) return; /* If the CREATE VIRTUAL TABLE statement is being entered for the ** first time (in other words if the virtual table is actually being ** created now instead of just being read out of sqlite_master) then ** do additional initialization work and store the statement text ** in the sqlite_master table. */ if (0 == db.init.busy) { string zStmt; string zWhere; int iDb; Vdbe v; /* Compute the complete text of the CREATE VIRTUAL TABLE statement */ if (pEnd != null) { pParse.sNameToken.n = pParse.sNameToken.z.Length;//(int)( pEnd.z - pParse.sNameToken.z ) + pEnd.n; } zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", pParse.sNameToken.z.Substring(0, pParse.sNameToken.n)); /* A slot for the record has already been allocated in the ** SQLITE_MASTER table. We just need to update that slot with all ** the information we've collected. ** ** The VM register number pParse.regRowid holds the rowid of an ** entry in the sqlite_master table tht was created for this vtab ** by sqlite3StartTable(). */ iDb = sqlite3SchemaToIndex(db, pTab.pSchema); sqlite3NestedParse(pParse, "UPDATE %Q.%s " + "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q " + "WHERE rowid=#%d", db.aDb[iDb].zName, SCHEMA_TABLE(iDb), pTab.zName, pTab.zName, zStmt, pParse.regRowid ); sqlite3DbFree(db, ref zStmt); v = sqlite3GetVdbe(pParse); sqlite3ChangeCookie(pParse, iDb); sqlite3VdbeAddOp2(v, OP_Expire, 0, 0); zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab.zName); sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, pTab.zName, sqlite3Strlen30(pTab.zName) + 1); } /* If we are rereading the sqlite_master table create the in-memory ** record of the table. The xConnect() method is not called until ** the first time the virtual table is used in an SQL statement. This ** allows a schema that contains virtual tables to be loaded before ** the required virtual table implementations are registered. */ else { Table pOld; Schema pSchema = pTab.pSchema; string zName = pTab.zName; int nName = sqlite3Strlen30(zName); Debug.Assert(sqlite3SchemaMutexHeld(db, 0, pSchema)); pOld = sqlite3HashInsert(ref pSchema.tblHash, zName, nName, pTab); if (pOld != null) { //db.mallocFailed = 1; Debug.Assert(pTab == pOld); /* Malloc must have failed inside HashInsert() */ return; } pParse.pNewTable = null; } } /* ** The parser calls this routine when it sees the first token ** of an argument to the module name in a CREATE VIRTUAL TABLE statement. */ static void sqlite3VtabArgInit(Parse pParse) { addArgumentToVtab(pParse); pParse.sArg.z = null; pParse.sArg.n = 0; } /* ** The parser calls this routine for each token after the first token ** in an argument to the module name in a CREATE VIRTUAL TABLE statement. */ static void sqlite3VtabArgExtend(Parse pParse, Token p) { Token pArg = pParse.sArg; if (pArg.z == null) { pArg.z = p.z; pArg.n = p.n; } else { //Debug.Assert( pArg.z< p.z ); pArg.n += p.n + 1;//(int)( p.z[p.n] - pArg.z ); } } /* ** Invoke a virtual table constructor (either xCreate or xConnect). The ** pointer to the function to invoke is passed as the fourth parameter ** to this procedure. */ static int vtabCallConstructor( sqlite3 db, Table pTab, Module pMod, smdxCreateConnect xConstruct, ref string pzErr ) { VtabCtx sCtx = new VtabCtx(); VTable pVTable; int rc; string[] azArg = pTab.azModuleArg; int nArg = pTab.nModuleArg; string zErr = null; string zModuleName = sqlite3MPrintf(db, "%s", pTab.zName); //if ( String.IsNullOrEmpty( zModuleName ) ) //{ // return SQLITE_NOMEM; //} pVTable = new VTable();//sqlite3DbMallocZero( db, sizeof( VTable ) ); //if ( null == pVTable ) //{ // sqlite3DbFree( db, ref zModuleName ); // return SQLITE_NOMEM; //} pVTable.db = db; pVTable.pMod = pMod; /* Invoke the virtual table constructor */ //assert( &db->pVtabCtx ); Debug.Assert(xConstruct != null); sCtx.pTab = pTab; sCtx.pVTable = pVTable; db.pVtabCtx = sCtx; rc = xConstruct(db, pMod.pAux, nArg, azArg, out pVTable.pVtab, out zErr); db.pVtabCtx = null; //if ( rc == SQLITE_NOMEM ) // db.mallocFailed = 1; if (SQLITE_OK != rc) { if (zErr == "") { pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName); } else { pzErr = sqlite3MPrintf(db, "%s", zErr); zErr = null;//sqlite3_free( zErr ); } sqlite3DbFree(db, ref pVTable); } else if (ALWAYS(pVTable.pVtab)) { /* Justification of ALWAYS(): A correct vtab constructor must allocate ** the sqlite3_vtab object if successful. */ pVTable.pVtab.pModule = pMod.pModule; pVTable.nRef = 1; if (sCtx.pTab != null) { string zFormat = "vtable constructor did not declare schema: %s"; pzErr = sqlite3MPrintf(db, zFormat, pTab.zName); sqlite3VtabUnlock(pVTable); rc = SQLITE_ERROR; } else { int iCol; /* If everything went according to plan, link the new VTable structure ** into the linked list headed by pTab->pVTable. Then loop through the ** columns of the table to see if any of them contain the token "hidden". ** If so, set the Column.isHidden flag and remove the token from ** the type string. */ pVTable.pNext = pTab.pVTable; pTab.pVTable = pVTable; for (iCol = 0; iCol < pTab.nCol; iCol++) { if (String.IsNullOrEmpty(pTab.aCol[iCol].zType)) continue; StringBuilder zType = new StringBuilder(pTab.aCol[iCol].zType); int nType; int i = 0; //if ( zType ) // continue; nType = sqlite3Strlen30(zType); if (sqlite3StrNICmp("hidden", 0, zType.ToString(), 6) != 0 || (zType.Length > 6 && zType[6] != ' ')) { for (i = 0; i < nType; i++) { if ((0 == sqlite3StrNICmp(" hidden", zType.ToString().Substring(i), 7)) && (i + 7 == zType.Length || (zType[i + 7] == '\0' || zType[i + 7] == ' ')) ) { i++; break; } } } if (i < nType) { int j; int nDel = 6 + (zType.Length > i + 6 ? 1 : 0); for (j = i; (j + nDel) < nType; j++) { zType[j] = zType[j + nDel]; } if (zType[i] == '\0' && i > 0) { Debug.Assert(zType[i - 1] == ' '); zType.Length = i;//[i - 1] = '\0'; } pTab.aCol[iCol].isHidden = 1; pTab.aCol[iCol].zType = zType.ToString().Substring(0, j); } } } } sqlite3DbFree(db, ref zModuleName); return rc; } /* ** This function is invoked by the parser to call the xConnect() method ** of the virtual table pTab. If an error occurs, an error code is returned ** and an error left in pParse. ** ** This call is a no-op if table pTab is not a virtual table. */ static int sqlite3VtabCallConnect(Parse pParse, Table pTab) { sqlite3 db = pParse.db; string zMod; Module pMod; int rc; Debug.Assert(pTab != null); if ((pTab.tabFlags & TF_Virtual) == 0 || sqlite3GetVTable(db, pTab) != null) { return SQLITE_OK; } /* Locate the required virtual table module */ zMod = pTab.azModuleArg[0]; pMod = (Module)sqlite3HashFind(db.aModule, zMod, sqlite3Strlen30(zMod), (Module)null); if (null == pMod) { string zModule = pTab.azModuleArg[0]; sqlite3ErrorMsg(pParse, "no such module: %s", zModule); rc = SQLITE_ERROR; } else { string zErr = null; rc = vtabCallConstructor(db, pTab, pMod, pMod.pModule.xConnect, ref zErr); if (rc != SQLITE_OK) { sqlite3ErrorMsg(pParse, "%s", zErr); } zErr = null;//sqlite3DbFree( db, zErr ); } return rc; } /* ** Grow the db.aVTrans[] array so that there is room for at least one ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise. */ static int growVTrans(sqlite3 db) { const int ARRAY_INCR = 5; /* Grow the sqlite3.aVTrans array if required */ if ((db.nVTrans % ARRAY_INCR) == 0) { //VTable** aVTrans; //int nBytes = sizeof( sqlite3_vtab* ) * ( db.nVTrans + ARRAY_INCR ); //aVTrans = sqlite3DbRealloc( db, (void)db.aVTrans, nBytes ); //if ( !aVTrans ) //{ // return SQLITE_NOMEM; //} //memset( &aVTrans[db.nVTrans], 0, sizeof( sqlite3_vtab* ) * ARRAY_INCR ); Array.Resize(ref db.aVTrans, db.nVTrans + ARRAY_INCR); } return SQLITE_OK; } /* ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should ** have already been reserved using growVTrans(). */ static void addToVTrans(sqlite3 db, VTable pVTab) { /* Add pVtab to the end of sqlite3.aVTrans */ db.aVTrans[db.nVTrans++] = pVTab; sqlite3VtabLock(pVTab); } /* ** This function is invoked by the vdbe to call the xCreate method ** of the virtual table named zTab in database iDb. ** ** If an error occurs, *pzErr is set to point an an English language ** description of the error and an SQLITE_XXX error code is returned. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr. */ static int sqlite3VtabCallCreate(sqlite3 db, int iDb, string zTab, ref string pzErr) { int rc = SQLITE_OK; Table pTab; Module pMod; string zMod; pTab = sqlite3FindTable(db, zTab, db.aDb[iDb].zName); Debug.Assert(pTab != null && (pTab.tabFlags & TF_Virtual) != 0 && null == pTab.pVTable); /* Locate the required virtual table module */ zMod = pTab.azModuleArg[0]; pMod = (Module)sqlite3HashFind(db.aModule, zMod, sqlite3Strlen30(zMod), (Module)null); /* If the module has been registered and includes a Create method, ** invoke it now. If the module has not been registered, return an ** error. Otherwise, do nothing. */ if (null == pMod) { pzErr = sqlite3MPrintf(db, "no such module: %s", zMod); rc = SQLITE_ERROR; } else { rc = vtabCallConstructor(db, pTab, pMod, pMod.pModule.xCreate, ref pzErr); } /* Justification of ALWAYS(): The xConstructor method is required to ** create a valid sqlite3_vtab if it returns SQLITE_OK. */ if (rc == SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab))) { rc = growVTrans(db); if (rc == SQLITE_OK) { addToVTrans(db, sqlite3GetVTable(db, pTab)); } } return rc; } /* ** This function is used to set the schema of a virtual table. It is only ** valid to call this function from within the xCreate() or xConnect() of a ** virtual table module. */ static int sqlite3_declare_vtab(sqlite3 db, string zCreateTable) { Parse pParse; int rc = SQLITE_OK; Table pTab; string zErr = ""; sqlite3_mutex_enter(db.mutex); if (null == db.pVtabCtx || null == (pTab = db.pVtabCtx.pTab)) { sqlite3Error(db, SQLITE_MISUSE, 0); sqlite3_mutex_leave(db.mutex); return SQLITE_MISUSE_BKPT(); } Debug.Assert((pTab.tabFlags & TF_Virtual) != 0); pParse = new Parse();//sqlite3StackAllocZero(db, sizeof(*pParse)); //if ( pParse == null ) //{ // rc = SQLITE_NOMEM; //} //else { pParse.declareVtab = 1; pParse.db = db; pParse.nQueryLoop = 1; if (SQLITE_OK == sqlite3RunParser(pParse, zCreateTable, ref zErr) && pParse.pNewTable != null //&& !db.mallocFailed && null == pParse.pNewTable.pSelect && (pParse.pNewTable.tabFlags & TF_Virtual) == 0 ) { if (null == pTab.aCol) { pTab.aCol = pParse.pNewTable.aCol; pTab.nCol = pParse.pNewTable.nCol; pParse.pNewTable.nCol = 0; pParse.pNewTable.aCol = null; } db.pVtabCtx.pTab = null; } else { sqlite3Error(db, SQLITE_ERROR, (zErr != null ? "%s" : null), zErr); zErr = null;//sqlite3DbFree( db, zErr ); rc = SQLITE_ERROR; } pParse.declareVtab = 0; if (pParse.pVdbe != null) { sqlite3VdbeFinalize(ref pParse.pVdbe); } sqlite3DeleteTable(db, ref pParse.pNewTable); //sqlite3StackFree( db, pParse ); } Debug.Assert((rc & 0xff) == rc); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db.mutex); return rc; } /* ** This function is invoked by the vdbe to call the xDestroy method ** of the virtual table named zTab in database iDb. This occurs ** when a DROP TABLE is mentioned. ** ** This call is a no-op if zTab is not a virtual table. */ static int sqlite3VtabCallDestroy(sqlite3 db, int iDb, string zTab) { int rc = SQLITE_OK; Table pTab; pTab = sqlite3FindTable(db, zTab, db.aDb[iDb].zName); if (ALWAYS(pTab != null && pTab.pVTable != null)) { VTable p = vtabDisconnectAll(db, pTab); Debug.Assert(rc == SQLITE_OK); object obj = p.pVtab; rc = p.pMod.pModule.xDestroy(ref obj); p.pVtab = null; /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */ if (rc == SQLITE_OK) { Debug.Assert(pTab.pVTable == p && p.pNext == null); p.pVtab = null; pTab.pVTable = null; sqlite3VtabUnlock(p); } } return rc; } /* ** This function invokes either the xRollback or xCommit method ** of each of the virtual tables in the sqlite3.aVTrans array. The method ** called is identified by the second argument, "offset", which is ** the offset of the method to call in the sqlite3_module structure. ** ** The array is cleared after invoking the callbacks. */ static void callFinaliser(sqlite3 db, int offset) { int i; if (db.aVTrans != null) { for (i = 0; i < db.nVTrans; i++) { VTable pVTab = db.aVTrans[i]; sqlite3_vtab p = pVTab.pVtab; if (p != null) { //int (*x)(sqlite3_vtab ); //x = *(int (*)(sqlite3_vtab ))((char )p.pModule + offset); //if( x ) x(p); if (offset == 0) { if (p.pModule.xCommit != null) p.pModule.xCommit(p); } else { if (p.pModule.xRollback != null) p.pModule.xRollback(p); } } pVTab.iSavepoint = 0; sqlite3VtabUnlock(pVTab); } sqlite3DbFree(db, ref db.aVTrans); db.nVTrans = 0; db.aVTrans = null; } } /* ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans ** array. Return the error code for the first error that occurs, or ** SQLITE_OK if all xSync operations are successful. ** ** Set *pzErrmsg to point to a buffer that should be released using ** sqlite3DbFree() containing an error message, if one is available. */ static int sqlite3VtabSync(sqlite3 db, ref string pzErrmsg) { int i; int rc = SQLITE_OK; VTable[] aVTrans = db.aVTrans; db.aVTrans = null; for (i = 0; rc == SQLITE_OK && i < db.nVTrans; i++) { smdxFunction x;//int (*x)(sqlite3_vtab ); sqlite3_vtab pVtab = aVTrans[i].pVtab; if (pVtab != null && (x = pVtab.pModule.xSync) != null) { rc = x(pVtab); //sqlite3DbFree(db, ref pzErrmsg); pzErrmsg = pVtab.zErrMsg;// sqlite3DbStrDup( db, pVtab.zErrMsg ); pVtab.zErrMsg = null;//sqlite3_free( ref pVtab.zErrMsg ); } } db.aVTrans = aVTrans; return rc; } /* ** Invoke the xRollback method of all virtual tables in the ** sqlite3.aVTrans array. Then clear the array itself. */ static int sqlite3VtabRollback(sqlite3 db) { callFinaliser(db, 1);//offsetof( sqlite3_module, xRollback ) ); return SQLITE_OK; } /* ** Invoke the xCommit method of all virtual tables in the ** sqlite3.aVTrans array. Then clear the array itself. */ static int sqlite3VtabCommit(sqlite3 db) { callFinaliser(db, 0);//offsetof( sqlite3_module, xCommit ) ); return SQLITE_OK; } /* ** If the virtual table pVtab supports the transaction interface ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is ** not currently open, invoke the xBegin method now. ** ** If the xBegin call is successful, place the sqlite3_vtab pointer ** in the sqlite3.aVTrans array. */ static int sqlite3VtabBegin(sqlite3 db, VTable pVTab) { int rc = SQLITE_OK; sqlite3_module pModule; /* Special case: If db.aVTrans is NULL and db.nVTrans is greater ** than zero, then this function is being called from within a ** virtual module xSync() callback. It is illegal to write to ** virtual module tables in this case, so return SQLITE_LOCKED. */ if (sqlite3VtabInSync(db)) { return SQLITE_LOCKED; } if (null == pVTab) { return SQLITE_OK; } pModule = pVTab.pVtab.pModule; if (pModule.xBegin != null) { int i; /* If pVtab is already in the aVTrans array, return early */ for (i = 0; i < db.nVTrans; i++) { if (db.aVTrans[i] == pVTab) { return SQLITE_OK; } } /* Invoke the xBegin method. If successful, add the vtab to the ** sqlite3.aVTrans[] array. */ rc = growVTrans(db); if (rc == SQLITE_OK) { rc = pModule.xBegin(pVTab.pVtab); if (rc == SQLITE_OK) { addToVTrans(db, pVTab); } } } return rc; } /* ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all ** virtual tables that currently have an open transaction. Pass iSavepoint ** as the second argument to the virtual table method invoked. ** ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with ** an open transaction is invoked. ** ** If any virtual table method returns an error code other than SQLITE_OK, ** processing is abandoned and the error returned to the caller of this ** function immediately. If all calls to virtual table methods are successful, ** SQLITE_OK is returned. */ static int sqlite3VtabSavepoint(sqlite3 db, int op, int iSavepoint) { int rc = SQLITE_OK; Debug.Assert(op == SAVEPOINT_RELEASE || op == SAVEPOINT_ROLLBACK || op == SAVEPOINT_BEGIN); Debug.Assert(iSavepoint >= 0); if (db.aVTrans != null) { int i; for (i = 0; rc == SQLITE_OK && i < db.nVTrans; i++) { VTable pVTab = db.aVTrans[i]; sqlite3_module pMod = pVTab.pMod.pModule; if (pMod.iVersion >= 2) { smdxFunctionArg xMethod = null; //int (*xMethod)(sqlite3_vtab *, int); switch (op) { case SAVEPOINT_BEGIN: xMethod = pMod.xSavepoint; pVTab.iSavepoint = iSavepoint + 1; break; case SAVEPOINT_ROLLBACK: xMethod = pMod.xRollbackTo; break; default: xMethod = pMod.xRelease; break; } if (xMethod != null && pVTab.iSavepoint > iSavepoint) { rc = xMethod(db.aVTrans[i].pVtab, iSavepoint); } } } } return rc; } /* ** The first parameter (pDef) is a function implementation. The ** second parameter (pExpr) is the first argument to this function. ** If pExpr is a column in a virtual table, then let the virtual ** table implementation have an opportunity to overload the function. ** ** This routine is used to allow virtual table implementations to ** overload MATCH, LIKE, GLOB, and REGEXP operators. ** ** Return either the pDef argument (indicating no change) or a ** new FuncDef structure that is marked as ephemeral using the ** SQLITE_FUNC_EPHEM flag. */ static FuncDef sqlite3VtabOverloadFunction( sqlite3 db, /* Database connection for reporting malloc problems */ FuncDef pDef, /* Function to possibly overload */ int nArg, /* Number of arguments to the function */ Expr pExpr /* First argument to the function */ ) { Table pTab; sqlite3_vtab pVtab; sqlite3_module pMod; dxFunc xFunc = null;//void (*xFunc)(sqlite3_context*,int,sqlite3_value*) = 0; object pArg = null; FuncDef pNew; int rc = 0; string zLowerName; string z; /* Check to see the left operand is a column in a virtual table */ if (NEVER(pExpr == null)) return pDef; if (pExpr.op != TK_COLUMN) return pDef; pTab = pExpr.pTab; if (NEVER(pTab == null)) return pDef; if ((pTab.tabFlags & TF_Virtual) == 0) return pDef; pVtab = sqlite3GetVTable(db, pTab).pVtab; Debug.Assert(pVtab != null); Debug.Assert(pVtab.pModule != null); pMod = (sqlite3_module)pVtab.pModule; if (pMod.xFindFunction == null) return pDef; /* Call the xFindFunction method on the virtual table implementation ** to see if the implementation wants to overload this function */ zLowerName = pDef.zName;//sqlite3DbStrDup(db, pDef.zName); if (zLowerName != null) { //for(z=(unsigned char)zLowerName; *z; z++){ // *z = sqlite3UpperToLower[*z]; //} rc = pMod.xFindFunction(pVtab, nArg, zLowerName.ToLowerInvariant(), ref xFunc, ref pArg); sqlite3DbFree(db, ref zLowerName); } if (rc == 0) { return pDef; } /* Create a new ephemeral function definition for the overloaded ** function */ //sqlite3DbMallocZero(db, sizeof(*pNew) // + sqlite3Strlen30(pDef.zName) + 1); //if ( pNew == null ) //{ // return pDef; //} pNew = pDef.Copy(); pNew.zName = pDef.zName; //pNew.zName = (char )&pNew[1]; //memcpy(pNew.zName, pDef.zName, sqlite3Strlen30(pDef.zName)+1); pNew.xFunc = xFunc; pNew.pUserData = pArg; pNew.flags |= SQLITE_FUNC_EPHEM; return pNew; } /* ** Make sure virtual table pTab is contained in the pParse.apVirtualLock[] ** array so that an OP_VBegin will get generated for it. Add pTab to the ** array if it is missing. If pTab is already in the array, this routine ** is a no-op. */ static void sqlite3VtabMakeWritable(Parse pParse, Table pTab) { Parse pToplevel = sqlite3ParseToplevel(pParse); int i, n; //Table[] apVtabLock = null; Debug.Assert(IsVirtual(pTab)); for (i = 0; i < pToplevel.nVtabLock; i++) { if (pTab == pToplevel.apVtabLock[i]) return; } n = pToplevel.apVtabLock == null ? 1 : pToplevel.apVtabLock.Length + 1;//(pToplevel.nVtabLock+1)*sizeof(pToplevel.apVtabLock[0]); //sqlite3_realloc( pToplevel.apVtabLock, n ); //if ( apVtabLock != null ) { Array.Resize(ref pToplevel.apVtabLock, n);// pToplevel.apVtabLock= apVtabLock; pToplevel.apVtabLock[pToplevel.nVtabLock++] = pTab; } //else //{ // pToplevel.db.mallocFailed = 1; //} } static int[] aMap = new int[] { SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE }; /* ** Return the ON CONFLICT resolution mode in effect for the virtual ** table update operation currently in progress. ** ** The results of this routine are undefined unless it is called from ** within an xUpdate method. */ static int sqlite3_vtab_on_conflict(sqlite3 db) { //static const unsigned char aMap[] = { // SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE //}; Debug.Assert(OE_Rollback == 1 && OE_Abort == 2 && OE_Fail == 3); Debug.Assert(OE_Ignore == 4 && OE_Replace == 5); Debug.Assert(db.vtabOnConflict >= 1 && db.vtabOnConflict <= 5); return (int)aMap[db.vtabOnConflict - 1]; } /* ** Call from within the xCreate() or xConnect() methods to provide ** the SQLite core with additional information about the behavior ** of the virtual table being implemented. */ static int sqlite3_vtab_config(sqlite3 db, int op, params object[] ap) { // TODO ...){ //va_list ap; int rc = SQLITE_OK; sqlite3_mutex_enter(db.mutex); va_start(ap, "op"); switch (op) { case SQLITE_VTAB_CONSTRAINT_SUPPORT: { VtabCtx p = db.pVtabCtx; if (null == p) { rc = SQLITE_MISUSE_BKPT(); } else { Debug.Assert(p.pTab == null || (p.pTab.tabFlags & TF_Virtual) != 0); p.pVTable.bConstraint = (Byte)va_arg(ap, (Int32)0); } break; } default: rc = SQLITE_MISUSE_BKPT(); break; } va_end(ref ap); if (rc != SQLITE_OK) sqlite3Error(db, rc, 0); sqlite3_mutex_leave(db.mutex); return rc; } #endif //* SQLITE_OMIT_VIRTUALTABLE */ } }
// ThreadTest.cs - NUnit Test Cases for the System.Threading.Thread class // // Authors // Eduardo Garcia Cebollero (kiwnix@yahoo.es) // Sebastien Pouliot <sebastien@ximian.com> // // (C) Eduardo Garcia Cebollero. // (C) Ximian, Inc. http://www.ximian.com // (C) 2004 Novell (http://www.novell.com) // using NUnit.Framework; using System; using System.Security.Principal; using System.Threading; namespace MonoTests.System.Threading { // These tests seem to hang the 2.0 framework. So they are disabled for now // Don't reenable them until you can run a few thousand times on an SMP box. [Category ("NotWorking")] public class ThreadedPrincipalTest : Assertion { public static void NoPrincipal () { AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.NoPrincipal); IPrincipal p = Thread.CurrentPrincipal; AssertNull ("Thread.CurrentPrincipal-1", p); Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null); AssertNotNull ("Thread.CurrentPrincipal-2", Thread.CurrentPrincipal); Thread.CurrentPrincipal = null; AssertNull ("Thread.CurrentPrincipal-3", Thread.CurrentPrincipal); // in this case we can return to null } public static void UnauthenticatedPrincipal () { AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.UnauthenticatedPrincipal); IPrincipal p = Thread.CurrentPrincipal; AssertNotNull ("Thread.CurrentPrincipal", p); Assert ("Type", (p is GenericPrincipal)); AssertEquals ("Name", String.Empty, p.Identity.Name); AssertEquals ("AuthenticationType", String.Empty, p.Identity.AuthenticationType); Assert ("IsAuthenticated", !p.Identity.IsAuthenticated); Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null); AssertNotNull ("Thread.CurrentPrincipal-2", Thread.CurrentPrincipal); Thread.CurrentPrincipal = null; AssertNotNull ("Thread.CurrentPrincipal-3", Thread.CurrentPrincipal); // in this case we can't return to null } public static void WindowsPrincipal () { AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.WindowsPrincipal); IPrincipal p = Thread.CurrentPrincipal; AssertNotNull ("Thread.CurrentPrincipal", p); Assert ("Type", (p is WindowsPrincipal)); AssertNotNull ("Name", p.Identity.Name); AssertNotNull ("AuthenticationType", p.Identity.AuthenticationType); Assert ("IsAuthenticated", p.Identity.IsAuthenticated); // note: we can switch from a WindowsPrincipal to a GenericPrincipal Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null); AssertNotNull ("Thread.CurrentPrincipal-2", Thread.CurrentPrincipal); Thread.CurrentPrincipal = null; AssertNotNull ("Thread.CurrentPrincipal-3", Thread.CurrentPrincipal); // in this case we can't return to null } } [TestFixture] [Category ("NotWorking")] public class ThreadTest : Assertion { //Some Classes to test as threads private class C1Test { public int cnt; public Thread thread1; public bool endm1; public bool endm2; public C1Test() { thread1 = (Thread)null; this.cnt = 0; endm1 = endm2 = false; } public void TestMethod() { while (cnt < 10) { cnt++; } endm1 = true; } public void TestMethod2() { if (!(thread1==(Thread)null) ) { thread1.Join(); } endm2 = true; } } private class C2Test { public int cnt; public bool run = false; public C2Test() { this.cnt = 0; } public void TestMethod() { run = true; while (true) { if (cnt < 1000) cnt++; else cnt = 0; } } } private class C3Test { public C1Test sub_class; public Thread sub_thread; public C3Test() { sub_class = new C1Test(); sub_thread = new Thread(new ThreadStart(sub_class.TestMethod)); } public void TestMethod1() { sub_thread.Start(); Thread.Sleep (100); sub_thread.Abort(); } } private class C4Test { public C1Test class1; public C1Test class2; public Thread thread1; public Thread thread2; public bool T1ON ; public bool T2ON ; public C4Test() { T1ON = false; T2ON = false; class1 = new C1Test(); class2 = new C1Test(); thread1 = new Thread(new ThreadStart(class1.TestMethod)); thread2 = new Thread(new ThreadStart(class2.TestMethod)); } public void TestMethod1() { thread1.Start(); TestUtil.WaitForAlive (thread1, "wait1"); T1ON = true; thread2.Start(); TestUtil.WaitForAlive (thread2, "wait2"); T2ON = true; thread1.Abort(); TestUtil.WaitForNotAlive (thread1, "wait3"); T1ON = false; thread2.Abort(); TestUtil.WaitForNotAlive (thread2, "wait4"); T2ON = false; } public void TestMethod2() { thread1.Start(); thread1.Join(); } } public void TestCtor1() { C1Test test1 = new C1Test(); try { Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); } catch (Exception e) { Fail ("#01 Unexpected Exception Thrown: " + e.ToString ()); } } [Category("NotDotNet")] public void TestStart() { { C1Test test1 = new C1Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); try { TestThread.Start(); } catch (Exception e) { Fail ("#12 Unexpected Exception Thrown: " + e.ToString ()); } TestThread.Join(); AssertEquals("#13 Thread Not started: ", 10,test1.cnt); } { bool errorThrown = false; C2Test test1 = new C2Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); TestThread.Start(); TestThread.Abort(); try { TestThread.Start(); } catch(ThreadStateException) { errorThrown = true; } Assert ("#14 no ThreadStateException trown", errorThrown); } { C2Test test1 = new C2Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); TestThread.Start(); while(!test1.run); bool started = (TestThread.ThreadState == ThreadState.Running); AssertEquals("#15 Thread Is not in the correct state: ", started , test1.run); TestThread.Abort(); } } public void TestApartment() { C2Test test1 = new C2Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); ApartmentState before = TestThread.ApartmentState; TestThread.Start(); TestUtil.WaitForAlive (TestThread, "wait5"); ApartmentState after = TestThread.ApartmentState; TestThread.Abort(); AssertEquals("#21 Apartment State Changed when not needed",before,after); } [Category("NotDotNet")] public void TestApartmentState() { C2Test test1 = new C2Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); ApartmentState before = TestThread.ApartmentState; TestThread.Start(); TestUtil.WaitForAlive (TestThread, "wait6"); ApartmentState after = TestThread.ApartmentState; TestThread.Abort(); AssertEquals("#31 Apartment State Changed when not needed: ",before,after); } public void TestPriority1() { C2Test test1 = new C2Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); try { TestThread.Priority=ThreadPriority.BelowNormal; ThreadPriority after = TestThread.Priority; TestThread.Start(); TestUtil.WaitForAlive (TestThread, "wait7"); ThreadPriority before = TestThread.Priority; AssertEquals("#41 Unexpected Priority Change: ",before,after); } finally { TestThread.Abort(); } } [Test] public void AbortUnstarted () { C2Test test1 = new C2Test(); Thread th = new Thread (new ThreadStart (test1.TestMethod)); th.Abort (); th.Start (); } [Category("NotWorking")] // this is a MonoTODO -> no support for Priority public void TestPriority2() { C2Test test1 = new C2Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); try { AssertEquals("#42 Incorrect Priority in New thread: ",ThreadPriority.Normal, TestThread.Priority); TestThread.Start(); TestUtil.WaitForAliveOrStop (TestThread, "wait8"); AssertEquals("#43 Incorrect Priority in Started thread: ",ThreadPriority.Normal, TestThread.Priority); } finally { TestThread.Abort(); } AssertEquals("#44 Incorrect Priority in Aborted thread: ",ThreadPriority.Normal, TestThread.Priority); } [Category("NotWorking")] // this is a MonoTODO -> no support for Priority public void TestPriority3() { C2Test test1 = new C2Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); try { TestThread.Start(); TestThread.Priority = ThreadPriority.Lowest; AssertEquals("#45A Incorrect Priority:",ThreadPriority.Lowest,TestThread.Priority); TestThread.Priority = ThreadPriority.BelowNormal; AssertEquals("#45B Incorrect Priority:",ThreadPriority.BelowNormal,TestThread.Priority); TestThread.Priority = ThreadPriority.Normal; AssertEquals("#45C Incorrect Priority:",ThreadPriority.Normal,TestThread.Priority); TestThread.Priority = ThreadPriority.AboveNormal; AssertEquals("#45D Incorrect Priority:",ThreadPriority.AboveNormal,TestThread.Priority); TestThread.Priority = ThreadPriority.Highest; AssertEquals("#45E Incorrect Priority:",ThreadPriority.Highest,TestThread.Priority); } finally { TestThread.Abort(); } } public void TestIsBackground1() { C2Test test1 = new C2Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); try { TestThread.Start(); TestUtil.WaitForAlive (TestThread, "wait9"); bool state = TestThread.IsBackground; Assert("#51 IsBackground not set at the default state: ",!(state)); } finally { TestThread.Abort(); } } public void TestIsBackground2() { C2Test test1 = new C2Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); TestThread.IsBackground = true; try { TestThread.Start(); } finally { TestThread.Abort(); } Assert("#52 Is Background Changed ot Start ",TestThread.IsBackground); } public void TestName() { C2Test test1 = new C2Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); try { TestThread.Start(); TestUtil.WaitForAlive (TestThread, "wait10"); string name = TestThread.Name; AssertEquals("#61 Name set when mustn't be set: ", name, (string)null); string newname = "Testing...."; TestThread.Name = newname; AssertEquals("#62 Name not set when must be set: ",TestThread.Name,newname); } finally { TestThread.Abort(); } } [Category("NotDotNet")] public void TestNestedThreads1() { C3Test test1 = new C3Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1)); try { TestThread.Start(); TestUtil.WaitForAlive (TestThread, "wait11"); } catch(Exception e) { Fail("#71 Unexpected Exception" + e.Message); } finally { TestThread.Abort(); } } public void TestNestedThreads2() { C4Test test1 = new C4Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1)); try { TestThread.Start(); } catch(Exception e) { Fail("#81 Unexpected Exception" + e.ToString()); } finally { TestThread.Abort(); } } public void TestJoin1() { C1Test test1 = new C1Test(); C1Test test2 = new C1Test(); Thread thread1 = new Thread(new ThreadStart(test1.TestMethod)); Thread thread2 = new Thread(new ThreadStart(test1.TestMethod2)); try { thread1.Start(); thread2.Start(); thread2.Join(); } catch(Exception e) { Fail("#91 Unexpected Exception " + e.ToString()); } finally { thread1.Abort(); thread2.Abort(); } } public void TestThreadState() { //TODO: Test The rest of the possible transitions C2Test test1 = new C2Test(); Thread TestThread = new Thread(new ThreadStart(test1.TestMethod)); AssertEquals("#101 Wrong Thread State",ThreadState.Unstarted,TestThread.ThreadState); try { TestThread.Start(); //while(!TestThread.IsAlive); //In the MS Documentation this is not necessary //but in the MS SDK it is Assert("#102 Wrong Thread State: " + TestThread.ThreadState.ToString(), TestThread.ThreadState == ThreadState.Running || (TestThread.ThreadState & ThreadState.Unstarted) != 0); } finally { TestThread.Abort(); } TestUtil.WaitForNotAlive (TestThread, "wait12"); // Docs say state will be Stopped, but Aborted happens sometimes (?) Assert("#103 Wrong Thread State: " + TestThread.ThreadState.ToString(), (ThreadState.Stopped & TestThread.ThreadState) != 0 || (ThreadState.Aborted & TestThread.ThreadState) != 0); } [Test] public void CurrentPrincipal_PrincipalPolicy_NoPrincipal () { // note: switching from PrincipalPolicy won't work inside the same thread // because as soon as a Principal object is created the Policy doesn't matter anymore Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.NoPrincipal)); try { t.Start (); t.Join (); } catch { t.Abort (); } } [Test] public void CurrentPrincipal_PrincipalPolicy_UnauthenticatedPrincipal () { // note: switching from PrincipalPolicy won't work inside the same thread // because as soon as a Principal object is created the Policy doesn't matter anymore Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.UnauthenticatedPrincipal)); try { t.Start (); t.Join (); } catch { t.Abort (); } } [Test] public void CurrentPrincipal_PrincipalPolicy_WindowsPrincipal () { // note: switching from PrincipalPolicy won't work inside the same thread // because as soon as a Principal object is created the Policy doesn't matter anymore Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.WindowsPrincipal)); try { t.Start (); t.Join (); } catch { t.Abort (); } } int counter = 0; [Category("NotDotNet")] public void TestSuspend () { Thread t = new Thread (new ThreadStart (DoCount)); t.IsBackground = true; t.Start (); CheckIsRunning ("t1", t); t.Suspend (); WaitSuspended ("t2", t); CheckIsNotRunning ("t3", t); t.Resume (); WaitResumed ("t4", t); CheckIsRunning ("t5", t); t.Abort (); TestUtil.WaitForNotAlive (t, "wait13"); CheckIsNotRunning ("t6", t); } [Category("NotDotNet")] [Category("NotWorking")] public void TestSuspendAbort () { Thread t = new Thread (new ThreadStart (DoCount)); t.IsBackground = true; t.Start (); CheckIsRunning ("t1", t); t.Suspend (); WaitSuspended ("t2", t); CheckIsNotRunning ("t3", t); t.Abort (); int n=0; while (t.IsAlive && n < 200) { Thread.Sleep (10); n++; } Assert ("Timeout while waiting for abort", n < 200); CheckIsNotRunning ("t6", t); } void CheckIsRunning (string s, Thread t) { int c = counter; Thread.Sleep (100); Assert (s, counter > c); } void CheckIsNotRunning (string s, Thread t) { int c = counter; Thread.Sleep (100); Assert (s, counter == c); } void WaitSuspended (string s, Thread t) { int n=0; ThreadState state = t.ThreadState; while ((state & ThreadState.Suspended) == 0) { Assert (s + ": expected SuspendRequested state", (state & ThreadState.SuspendRequested) != 0); Thread.Sleep (10); n++; Assert (s + ": failed to suspend", n < 100); state = t.ThreadState; } Assert (s + ": SuspendRequested state not expected", (state & ThreadState.SuspendRequested) == 0); } void WaitResumed (string s, Thread t) { int n=0; while ((t.ThreadState & ThreadState.Suspended) != 0) { Thread.Sleep (10); n++; Assert (s + ": failed to resume", n < 100); } } public void DoCount () { while (true) { counter++; Thread.Sleep (1); } } } public class TestUtil { public static void WaitForNotAlive (Thread t, string s) { WhileAlive (t, true, s); } public static void WaitForAlive (Thread t, string s) { WhileAlive (t, false, s); } public static bool WaitForAliveOrStop (Thread t, string s) { return WhileAliveOrStop (t, false, s); } public static void WhileAlive (Thread t, bool alive, string s) { DateTime ti = DateTime.Now; while (t.IsAlive == alive) { if ((DateTime.Now - ti).TotalSeconds > 10) { if (alive) Assertion.Fail ("Timeout while waiting for not alive state. " + s); else Assertion.Fail ("Timeout while waiting for alive state. " + s); } } } public static bool WhileAliveOrStop (Thread t, bool alive, string s) { DateTime ti = DateTime.Now; while (t.IsAlive == alive) { if (t.ThreadState == ThreadState.Stopped) return false; if ((DateTime.Now - ti).TotalSeconds > 10) { if (alive) Assertion.Fail ("Timeout while waiting for not alive state. " + s); else Assertion.Fail ("Timeout while waiting for alive state. " + s); } } return true; } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using ESRI.ArcGIS.ArcMapUI; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Editor; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Framework; using ESRI.ArcGIS.esriSystem; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace AngleAngle { class AngleAngleCstr : IShapeConstructor, IPersist { IEditor m_editor; IEditSketch3 m_edSketch; ISnappingEnvironment m_snappingEnv; IPointSnapper m_snapper; ISnappingFeedback m_snappingFeedback; // Declare 3 points IPoint m_firstPoint; IPoint m_secondPoint; IPoint m_activePoint; // Declare 2 angles double m_firstAngle; double m_secondAngle; enum ToolPhase { Inactive, SecondPoint, Intersection } ToolPhase m_etoolPhase; #region IShapeConstructor Members public void Activate() { } public bool Active { get { return true; } } public void AddPoint(IPoint point, bool Clone, bool allowUndo) { } public IPoint Anchor { get { return Anchor; } } public double AngleConstraint { get { return AngleConstraint; } set { AngleConstraint = value; } } public esriSketchConstraint Constraint { get { return Constraint; } set { Constraint = value; } } public int Cursor { get { return 0; } } public void Deactivate() { } public double DistanceConstraint { get { return DistanceConstraint; } set { DistanceConstraint = value; } } public bool Enabled { get { return true; } } public string ID { get { return ("Angle Angle Constructor"); } } public void Initialize(IEditor pEditor) { // Initialize the constructor m_editor = pEditor as IEditor; m_edSketch = pEditor as IEditSketch3; //Get the snap environment m_snappingEnv = m_editor.Parent.FindExtensionByName("ESRI Snapping") as ISnappingEnvironment; m_snapper = m_snappingEnv.PointSnapper; m_snappingFeedback = new SnappingFeedbackClass(); m_snappingFeedback.Initialize(m_editor.Parent, m_snappingEnv, true); m_firstPoint = new PointClass(); m_secondPoint = new PointClass(); m_activePoint = new PointClass(); // Set the phase to inactive so we start at the beginning m_etoolPhase = ToolPhase.Inactive; } public bool IsStreaming { get { return IsStreaming; } set { IsStreaming = value; } } public IPoint Location { get { return Location; } } public bool OnContextMenu(int X, int Y) { return true; } public void OnKeyDown(int keyState, int shift) { // If the escape key is used, throw away the calculated point if (keyState == (int)Keys.Escape) m_etoolPhase = ToolPhase.Inactive; } public void OnKeyUp(int keyState, int shift) { } public void OnMouseDown(int Button, int shift, int X, int Y) { if (Button != (int)Keys.LButton) return; switch (m_etoolPhase) { case (ToolPhase.Inactive): GetFirstPoint(); break; case (ToolPhase.SecondPoint): GetSecondPoint(); break; case (ToolPhase.Intersection): GetIntersection(); break; } } public void OnMouseMove(int Button, int shift, int X, int Y) { //Snap the mouse location if (m_etoolPhase != ToolPhase.Intersection) { m_activePoint = m_editor.Display.DisplayTransformation.ToMapPoint(X, Y); ISnappingResult snapResult = m_snapper.Snap(m_activePoint); m_snappingFeedback.Update(snapResult, 0); if (snapResult != null) m_activePoint = snapResult.Location; } } public void OnMouseUp(int Button, int shift, int X, int Y) { } public void Refresh(int hdc) { m_snappingFeedback.Refresh(hdc); } public void SketchModified() { } #endregion private void GetFirstPoint() { INumberDialog numDialog = new NumberDialogClass(); // Set first point to the active point which may have been snapped m_firstPoint = m_activePoint; // Get the angle if (numDialog.DoModal("Angle 1", 45, 2, m_editor.Display.hWnd)) { m_firstAngle = numDialog.Value * Math.PI / 180; m_etoolPhase = ToolPhase.SecondPoint; } } private void GetSecondPoint() { INumberDialog numDialog = new NumberDialogClass(); // Set the second point equal to the active point which may have been snapped m_secondPoint = m_activePoint; // Get the angle if (numDialog.DoModal("Angle 2", -45, 2, m_editor.Display.hWnd)) { m_secondAngle = numDialog.Value * Math.PI / 180; } else { m_etoolPhase = ToolPhase.Inactive; return; } // Get the intersection point IConstructPoint constructPoint = new PointClass(); constructPoint.ConstructAngleIntersection(m_firstPoint, m_firstAngle, m_secondPoint, m_secondAngle); IPoint point = constructPoint as IPoint; if (point.IsEmpty) { m_etoolPhase = ToolPhase.Inactive; MessageBox.Show("No Point Calculated"); return; } // Draw the calculated intersection point and erase previous snap feedback m_activePoint = point; m_etoolPhase = ToolPhase.Intersection; m_snappingFeedback.Update(null, 0); DrawPoint(m_activePoint); } private void GetIntersection() { IEditSketch editSketch = m_editor as IEditSketch; editSketch.AddPoint(m_activePoint, true); // Set the phase to inactive, back to beginning m_etoolPhase = ToolPhase.Inactive; } private void DrawPoint(IPoint pPoint) { //Draw a red graphic dot on the display at the given point location IRgbColor color = null; ISimpleMarkerSymbol marker = null; IAppDisplay appDisplay = m_editor.Display as IAppDisplay; //Set the symbol (red, size 8) color = new RgbColor(); color.Red = 255; color.Green = 0; color.Blue = 0; marker = new SimpleMarkerSymbol(); marker.Color = color; marker.Size = 8; //Draw the point appDisplay.StartDrawing(0, (short)esriScreenCache.esriNoScreenCache); appDisplay.SetSymbol(marker as ISymbol); appDisplay.DrawPoint(pPoint); appDisplay.FinishDrawing(); } #region IPersist Members public void GetClassID(out Guid pClassID) { //Explicitly set a guid. Used to set command.checked property pClassID = new Guid("edb83080-999d-11de-8a39-0800200c9a66"); } #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.InteropServices; using System.Security; namespace System.IO.Compression { /// <summary> /// Provides a wrapper around the ZLib decompression API. /// </summary> internal sealed class Inflater : IDisposable { private const int MinWindowBits = -15; // WindowBits must be between -8..-15 to ignore the header, 8..15 for private const int MaxWindowBits = 47; // zlib headers, 24..31 for GZip headers, or 40..47 for either Zlib or GZip private bool _finished; // Whether the end of the stream has been reached private bool _isDisposed; // Prevents multiple disposals private int _windowBits; // The WindowBits parameter passed to Inflater construction private ZLibNative.ZLibStreamHandle _zlibStream; // The handle to the primary underlying zlib stream private GCHandle _inputBufferHandle; // The handle to the buffer that provides input to _zlibStream private readonly long _uncompressedSize; private long _currentInflatedCount; private object SyncLock => this; // Used to make writing to unmanaged structures atomic /// <summary> /// Initialized the Inflater with the given windowBits size /// </summary> internal Inflater(int windowBits, long uncompressedSize = -1) { Debug.Assert(windowBits >= MinWindowBits && windowBits <= MaxWindowBits); _finished = false; _isDisposed = false; _windowBits = windowBits; InflateInit(windowBits); _uncompressedSize = uncompressedSize; } public int AvailableOutput => (int)_zlibStream.AvailOut; /// <summary> /// Returns true if the end of the stream has been reached. /// </summary> public bool Finished() => _finished; public unsafe bool Inflate(out byte b) { fixed (byte* bufPtr = &b) { int bytesRead = InflateVerified(bufPtr, 1); Debug.Assert(bytesRead == 0 || bytesRead == 1); return bytesRead != 0; } } public unsafe int Inflate(byte[] bytes, int offset, int length) { // If Inflate is called on an invalid or unready inflater, return 0 to indicate no bytes have been read. if (length == 0) return 0; Debug.Assert(null != bytes, "Can't pass in a null output buffer!"); fixed (byte* bufPtr = bytes) { return InflateVerified(bufPtr + offset, length); } } public unsafe int Inflate(Span<byte> destination) { // If Inflate is called on an invalid or unready inflater, return 0 to indicate no bytes have been read. if (destination.Length == 0) return 0; fixed (byte* bufPtr = &MemoryMarshal.GetReference(destination)) { return InflateVerified(bufPtr, destination.Length); } } public unsafe int InflateVerified(byte* bufPtr, int length) { // State is valid; attempt inflation try { int bytesRead = 0; if (_uncompressedSize == -1) { ReadOutput(bufPtr, length, out bytesRead); } else { if (_uncompressedSize > _currentInflatedCount) { length = (int)Math.Min(length, _uncompressedSize - _currentInflatedCount); ReadOutput(bufPtr, length, out bytesRead); _currentInflatedCount += bytesRead; } else { _finished = true; _zlibStream.AvailIn = 0; } } return bytesRead; } finally { // Before returning, make sure to release input buffer if necessary: if (0 == _zlibStream.AvailIn && _inputBufferHandle.IsAllocated) { DeallocateInputBufferHandle(); } } } private unsafe void ReadOutput(byte* bufPtr, int length, out int bytesRead) { if (ReadInflateOutput(bufPtr, length, ZLibNative.FlushCode.NoFlush, out bytesRead) == ZLibNative.ErrorCode.StreamEnd) { if (!NeedsInput() && IsGzipStream() && _inputBufferHandle.IsAllocated) { _finished = ResetStreamForLeftoverInput(); } else { _finished = true; } } } /// <summary> /// If this stream has some input leftover that hasn't been processed then we should /// check if it is another GZip file concatenated with this one. /// /// Returns false if the leftover input is another GZip data stream. /// </summary> private unsafe bool ResetStreamForLeftoverInput() { Debug.Assert(!NeedsInput()); Debug.Assert(IsGzipStream()); Debug.Assert(_inputBufferHandle.IsAllocated); lock (SyncLock) { IntPtr nextInPtr = _zlibStream.NextIn; byte* nextInPointer = (byte*)nextInPtr.ToPointer(); uint nextAvailIn = _zlibStream.AvailIn; // Check the leftover bytes to see if they start with he gzip header ID bytes if (*nextInPointer != ZLibNative.GZip_Header_ID1 || (nextAvailIn > 1 && *(nextInPointer + 1) != ZLibNative.GZip_Header_ID2)) { return true; } // Trash our existing zstream. _zlibStream.Dispose(); // Create a new zstream InflateInit(_windowBits); // SetInput on the new stream to the bits remaining from the last stream _zlibStream.NextIn = nextInPtr; _zlibStream.AvailIn = nextAvailIn; _finished = false; } return false; } internal bool IsGzipStream() => _windowBits >= 24 && _windowBits <= 31; public bool NeedsInput() => _zlibStream.AvailIn == 0; public void SetInput(byte[] inputBuffer, int startIndex, int count) { Debug.Assert(NeedsInput(), "We have something left in previous input!"); Debug.Assert(inputBuffer != null); Debug.Assert(startIndex >= 0 && count >= 0 && count + startIndex <= inputBuffer.Length); Debug.Assert(!_inputBufferHandle.IsAllocated); if (0 == count) return; lock (SyncLock) { _inputBufferHandle = GCHandle.Alloc(inputBuffer, GCHandleType.Pinned); _zlibStream.NextIn = _inputBufferHandle.AddrOfPinnedObject() + startIndex; _zlibStream.AvailIn = (uint)count; _finished = false; } } private void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) _zlibStream.Dispose(); if (_inputBufferHandle.IsAllocated) DeallocateInputBufferHandle(); _isDisposed = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Inflater() { Dispose(false); } /// <summary> /// Creates the ZStream that will handle inflation. /// </summary> private void InflateInit(int windowBits) { ZLibNative.ErrorCode error; try { error = ZLibNative.CreateZLibStreamForInflate(out _zlibStream, windowBits); } catch (Exception exception) // could not load the ZLib dll { throw new ZLibException(SR.ZLibErrorDLLLoadError, exception); } switch (error) { case ZLibNative.ErrorCode.Ok: // Successful initialization return; case ZLibNative.ErrorCode.MemError: // Not enough memory throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage()); case ZLibNative.ErrorCode.VersionError: //zlib library is incompatible with the version assumed throw new ZLibException(SR.ZLibErrorVersionMismatch, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage()); case ZLibNative.ErrorCode.StreamError: // Parameters are invalid throw new ZLibException(SR.ZLibErrorIncorrectInitParameters, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage()); default: throw new ZLibException(SR.ZLibErrorUnexpected, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage()); } } /// <summary> /// Wrapper around the ZLib inflate function, configuring the stream appropriately. /// </summary> private unsafe ZLibNative.ErrorCode ReadInflateOutput(byte* bufPtr, int length, ZLibNative.FlushCode flushCode, out int bytesRead) { lock (SyncLock) { _zlibStream.NextOut = (IntPtr)bufPtr; _zlibStream.AvailOut = (uint)length; ZLibNative.ErrorCode errC = Inflate(flushCode); bytesRead = length - (int)_zlibStream.AvailOut; return errC; } } /// <summary> /// Wrapper around the ZLib inflate function /// </summary> private ZLibNative.ErrorCode Inflate(ZLibNative.FlushCode flushCode) { ZLibNative.ErrorCode errC; try { errC = _zlibStream.Inflate(flushCode); } catch (Exception cause) // could not load the Zlib DLL correctly { throw new ZLibException(SR.ZLibErrorDLLLoadError, cause); } switch (errC) { case ZLibNative.ErrorCode.Ok: // progress has been made inflating case ZLibNative.ErrorCode.StreamEnd: // The end of the input stream has been reached return errC; case ZLibNative.ErrorCode.BufError: // No room in the output buffer - inflate() can be called again with more space to continue return errC; case ZLibNative.ErrorCode.MemError: // Not enough memory to complete the operation throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "inflate_", (int)errC, _zlibStream.GetErrorMessage()); case ZLibNative.ErrorCode.DataError: // The input data was corrupted (input stream not conforming to the zlib format or incorrect check value) throw new InvalidDataException(SR.UnsupportedCompression); case ZLibNative.ErrorCode.StreamError: //the stream structure was inconsistent (for example if next_in or next_out was NULL), throw new ZLibException(SR.ZLibErrorInconsistentStream, "inflate_", (int)errC, _zlibStream.GetErrorMessage()); default: throw new ZLibException(SR.ZLibErrorUnexpected, "inflate_", (int)errC, _zlibStream.GetErrorMessage()); } } /// <summary> /// Frees the GCHandle being used to store the input buffer /// </summary> private void DeallocateInputBufferHandle() { Debug.Assert(_inputBufferHandle.IsAllocated); lock (SyncLock) { _zlibStream.AvailIn = 0; _zlibStream.NextIn = ZLibNative.ZNullPtr; _inputBufferHandle.Free(); } } } }
using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.Json; using System.Text.RegularExpressions; using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources.Annotations; using JsonApiDotNetCore.Serialization; using JsonApiDotNetCore.Serialization.Objects; using UnitTests.TestModels; using Xunit; namespace UnitTests.Serialization.Server { public sealed class ResponseSerializerTests : SerializerTestsSetup { [Fact] public void SerializeSingle_ResourceWithDefaultTargetFields_CanSerialize() { // Arrange var resource = new TestResource { Id = 1, StringField = "value", NullableIntField = 123 }; ResponseSerializer<TestResource> serializer = GetResponseSerializer<TestResource>(); // Act string serialized = serializer.SerializeSingle(resource); // Assert const string expectedFormatted = @"{ ""data"":{ ""type"":""testResource"", ""id"":""1"", ""attributes"":{ ""stringField"":""value"", ""dateTimeField"":""0001-01-01T00:00:00"", ""nullableDateTimeField"":null, ""intField"":0, ""nullableIntField"":123, ""guidField"":""00000000-0000-0000-0000-000000000000"", ""complexField"":null } } }"; string expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); } [Fact] public void SerializeMany_ResourceWithDefaultTargetFields_CanSerialize() { // Arrange var resource = new TestResource { Id = 1, StringField = "value", NullableIntField = 123 }; ResponseSerializer<TestResource> serializer = GetResponseSerializer<TestResource>(); // Act string serialized = serializer.SerializeMany(resource.AsArray()); // Assert const string expectedFormatted = @"{ ""data"":[{ ""type"":""testResource"", ""id"":""1"", ""attributes"":{ ""stringField"":""value"", ""dateTimeField"":""0001-01-01T00:00:00"", ""nullableDateTimeField"":null, ""intField"":0, ""nullableIntField"":123, ""guidField"":""00000000-0000-0000-0000-000000000000"", ""complexField"":null } }] }"; string expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); } [Fact] public void SerializeSingle_ResourceWithIncludedRelationships_CanSerialize() { // Arrange var resource = new MultipleRelationshipsPrincipalPart { Id = 1, PopulatedToOne = new OneToOneDependent { Id = 10 }, PopulatedToManies = new HashSet<OneToManyDependent> { new() { Id = 20 } } }; ResourceContext resourceContext = ResourceGraph.GetResourceContext<MultipleRelationshipsPrincipalPart>(); List<IEnumerable<RelationshipAttribute>> chain = resourceContext.Relationships.Select(relationship => relationship.AsEnumerable()).ToList(); ResponseSerializer<MultipleRelationshipsPrincipalPart> serializer = GetResponseSerializer<MultipleRelationshipsPrincipalPart>(chain); // Act string serialized = serializer.SerializeSingle(resource); // Assert const string expectedFormatted = @"{ ""data"":{ ""type"":""multiPrincipals"", ""id"":""1"", ""attributes"":{ ""attributeMember"":null }, ""relationships"":{ ""populatedToOne"":{ ""data"":{ ""type"":""oneToOneDependents"", ""id"":""10"" } }, ""emptyToOne"": { ""data"":null }, ""populatedToManies"":{ ""data"":[ { ""type"":""oneToManyDependents"", ""id"":""20"" } ] }, ""emptyToManies"": { ""data"":[ ] }, ""multi"":{ ""data"":null } } }, ""included"":[ { ""type"":""oneToOneDependents"", ""id"":""10"", ""attributes"":{ ""attributeMember"":null } }, { ""type"":""oneToManyDependents"", ""id"":""20"", ""attributes"":{ ""attributeMember"":null } } ] }"; string expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); } [Fact] public void SerializeSingle_ResourceWithDeeplyIncludedRelationships_CanSerialize() { // Arrange var deeplyIncludedResource = new OneToManyPrincipal { Id = 30, AttributeMember = "deep" }; var includedResource = new OneToManyDependent { Id = 20, Principal = deeplyIncludedResource }; var resource = new MultipleRelationshipsPrincipalPart { Id = 10, PopulatedToManies = new HashSet<OneToManyDependent> { includedResource } }; ResourceContext outerResourceContext = ResourceGraph.GetResourceContext<MultipleRelationshipsPrincipalPart>(); List<List<RelationshipAttribute>> chains = outerResourceContext.Relationships.Select(relationship => { List<RelationshipAttribute> chain = relationship.AsList(); if (relationship.PublicName != "populatedToManies") { return chain; } ResourceContext innerResourceContext = ResourceGraph.GetResourceContext<OneToManyDependent>(); chain.AddRange(innerResourceContext.Relationships); return chain; }).ToList(); ResponseSerializer<MultipleRelationshipsPrincipalPart> serializer = GetResponseSerializer<MultipleRelationshipsPrincipalPart>(chains); // Act string serialized = serializer.SerializeSingle(resource); // Assert const string expectedFormatted = @"{ ""data"":{ ""type"":""multiPrincipals"", ""id"":""10"", ""attributes"":{ ""attributeMember"":null }, ""relationships"":{ ""populatedToOne"":{ ""data"":null }, ""emptyToOne"":{ ""data"":null }, ""populatedToManies"":{ ""data"":[ { ""type"":""oneToManyDependents"", ""id"":""20"" } ] }, ""emptyToManies"":{ ""data"":[] }, ""multi"":{ ""data"":null } } }, ""included"":[ { ""type"":""oneToManyDependents"", ""id"":""20"", ""attributes"":{ ""attributeMember"":null }, ""relationships"":{ ""principal"":{ ""data"":{ ""type"":""oneToManyPrincipals"", ""id"":""30"" } } } }, { ""type"":""oneToManyPrincipals"", ""id"":""30"", ""attributes"":{ ""attributeMember"":""deep"" } } ] }"; string expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); } [Fact] public void SerializeSingle_Null_CanSerialize() { // Arrange ResponseSerializer<TestResource> serializer = GetResponseSerializer<TestResource>(); // Act string serialized = serializer.SerializeSingle(null); // Assert const string expectedFormatted = @"{ ""data"": null }"; string expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); } [Fact] public void SerializeList_EmptyList_CanSerialize() { // Arrange ResponseSerializer<TestResource> serializer = GetResponseSerializer<TestResource>(); // Act string serialized = serializer.SerializeMany(new List<TestResource>()); // Assert const string expectedFormatted = @"{ ""data"": [] }"; string expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); } [Fact] public void SerializeSingle_ResourceWithLinksEnabled_CanSerialize() { // Arrange var resource = new OneToManyPrincipal { Id = 10 }; ResponseSerializer<OneToManyPrincipal> serializer = GetResponseSerializer<OneToManyPrincipal>(topLinks: DummyTopLevelLinks, relationshipLinks: DummyRelationshipLinks, resourceLinks: DummyResourceLinks); // Act string serialized = serializer.SerializeSingle(resource); // Assert const string expectedFormatted = @"{ ""links"":{ ""self"":""http://www.dummy.com/dummy-self-link"", ""first"":""http://www.dummy.com/dummy-first-link"", ""last"":""http://www.dummy.com/dummy-last-link"", ""prev"":""http://www.dummy.com/dummy-prev-link"", ""next"":""http://www.dummy.com/dummy-next-link"" }, ""data"":{ ""type"":""oneToManyPrincipals"", ""id"":""10"", ""attributes"":{ ""attributeMember"":null }, ""relationships"":{ ""dependents"":{ ""links"":{ ""self"":""http://www.dummy.com/dummy-relationship-self-link"", ""related"":""http://www.dummy.com/dummy-relationship-related-link"" } } }, ""links"":{ ""self"":""http://www.dummy.com/dummy-resource-self-link"" } } }"; string expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); } [Fact] public void SerializeSingle_ResourceWithMeta_IncludesMetaInResult() { // Arrange var meta = new Dictionary<string, object> { ["test"] = "meta" }; var resource = new OneToManyPrincipal { Id = 10 }; ResponseSerializer<OneToManyPrincipal> serializer = GetResponseSerializer<OneToManyPrincipal>(metaDict: meta); // Act string serialized = serializer.SerializeSingle(resource); // Assert const string expectedFormatted = @"{ ""data"":{ ""type"":""oneToManyPrincipals"", ""id"":""10"", ""attributes"":{ ""attributeMember"":null } }, ""meta"":{ ""test"": ""meta"" } }"; string expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); } [Fact] public void SerializeSingle_NullWithLinksAndMeta_StillShowsLinksAndMeta() { // Arrange var meta = new Dictionary<string, object> { ["test"] = "meta" }; ResponseSerializer<OneToManyPrincipal> serializer = GetResponseSerializer<OneToManyPrincipal>(metaDict: meta, topLinks: DummyTopLevelLinks, relationshipLinks: DummyRelationshipLinks, resourceLinks: DummyResourceLinks); // Act string serialized = serializer.SerializeSingle(null); // Assert const string expectedFormatted = @"{ ""links"":{ ""self"":""http://www.dummy.com/dummy-self-link"", ""first"":""http://www.dummy.com/dummy-first-link"", ""last"":""http://www.dummy.com/dummy-last-link"", ""prev"":""http://www.dummy.com/dummy-prev-link"", ""next"":""http://www.dummy.com/dummy-next-link"" }, ""data"": null, ""meta"":{ ""test"": ""meta"" } }"; string expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); } [Fact] public void SerializeError_Error_CanSerialize() { // Arrange var error = new ErrorObject(HttpStatusCode.InsufficientStorage) { Title = "title", Detail = "detail" }; var errorDocument = new Document { Errors = error.AsList() }; string expectedJson = JsonSerializer.Serialize(new { errors = new[] { new { id = error.Id, status = "507", title = "title", detail = "detail" } } }); ResponseSerializer<OneToManyPrincipal> serializer = GetResponseSerializer<OneToManyPrincipal>(); // Act string result = serializer.Serialize(errorDocument); // Assert Assert.Equal(expectedJson, result); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// RouteFiltersOperations operations. /// </summary> public partial interface IRouteFiltersOperations { /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='expand'> /// Expands referenced express route bgp peering resources. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RouteFilter>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RouteFilter>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RouteFilter>> UpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route filters in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RouteFilter>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route filters in a subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RouteFilter>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RouteFilter>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RouteFilter>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route filters in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RouteFilter>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route filters in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RouteFilter>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Lucene.Net.Index { using System; using Bits = Lucene.Net.Util.Bits; /* * 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 Codec = Lucene.Net.Codecs.Codec; using Directory = Lucene.Net.Store.Directory; using DocValuesConsumer = Lucene.Net.Codecs.DocValuesConsumer; using DocValuesType_e = Lucene.Net.Index.FieldInfo.DocValuesType_e; using FieldInfosWriter = Lucene.Net.Codecs.FieldInfosWriter; using FieldsConsumer = Lucene.Net.Codecs.FieldsConsumer; using InfoStream = Lucene.Net.Util.InfoStream; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; using StoredFieldsWriter = Lucene.Net.Codecs.StoredFieldsWriter; using TermVectorsWriter = Lucene.Net.Codecs.TermVectorsWriter; /// <summary> /// The SegmentMerger class combines two or more Segments, represented by an /// IndexReader, into a single Segment. Call the merge method to combine the /// segments. /// </summary> /// <seealso cref= #merge </seealso> public sealed class SegmentMerger { private readonly Directory Directory; private readonly int TermIndexInterval; private readonly Codec Codec; private readonly IOContext Context; private readonly MergeState MergeState; private readonly FieldInfos.Builder FieldInfosBuilder; // note, just like in codec apis Directory 'dir' is NOT the same as segmentInfo.dir!! public SegmentMerger(IList<AtomicReader> readers, SegmentInfo segmentInfo, InfoStream infoStream, Directory dir, int termIndexInterval, MergeState.CheckAbort checkAbort, FieldInfos.FieldNumbers fieldNumbers, IOContext context, bool validate) { // validate incoming readers if (validate) { foreach (AtomicReader reader in readers) { reader.CheckIntegrity(); } } MergeState = new MergeState(readers, segmentInfo, infoStream, checkAbort); Directory = dir; this.TermIndexInterval = termIndexInterval; this.Codec = segmentInfo.Codec; this.Context = context; this.FieldInfosBuilder = new FieldInfos.Builder(fieldNumbers); MergeState.SegmentInfo.DocCount = SetDocMaps(); } /// <summary> /// True if any merging should happen </summary> internal bool ShouldMerge() { return MergeState.SegmentInfo.DocCount > 0; } /// <summary> /// Merges the readers into the directory passed to the constructor </summary> /// <returns> The number of documents that were merged </returns> /// <exception cref="CorruptIndexException"> if the index is corrupt </exception> /// <exception cref="IOException"> if there is a low-level IO error </exception> public MergeState Merge() { if (!ShouldMerge()) { throw new InvalidOperationException("Merge would result in 0 document segment"); } // NOTE: it's important to add calls to // checkAbort.work(...) if you make any changes to this // method that will spend alot of time. The frequency // of this check impacts how long // IndexWriter.close(false) takes to actually stop the // threads. MergeFieldInfos(); SetMatchingSegmentReaders(); long t0 = 0; if (MergeState.InfoStream.IsEnabled("SM")) { t0 = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; } int numMerged = MergeFields(); if (MergeState.InfoStream.IsEnabled("SM")) { long t1 = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; MergeState.InfoStream.Message("SM", ((t1 - t0) / 1000000) + " msec to merge stored fields [" + numMerged + " docs]"); } Debug.Assert(numMerged == MergeState.SegmentInfo.DocCount); SegmentWriteState segmentWriteState = new SegmentWriteState(MergeState.InfoStream, Directory, MergeState.SegmentInfo, MergeState.FieldInfos, TermIndexInterval, null, Context); if (MergeState.InfoStream.IsEnabled("SM")) { t0 = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; } MergeTerms(segmentWriteState); if (MergeState.InfoStream.IsEnabled("SM")) { long t1 = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; MergeState.InfoStream.Message("SM", ((t1 - t0) / 1000000) + " msec to merge postings [" + numMerged + " docs]"); } if (MergeState.InfoStream.IsEnabled("SM")) { t0 = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; } if (MergeState.FieldInfos.HasDocValues()) { MergeDocValues(segmentWriteState); } if (MergeState.InfoStream.IsEnabled("SM")) { long t1 = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; MergeState.InfoStream.Message("SM", ((t1 - t0) / 1000000) + " msec to merge doc values [" + numMerged + " docs]"); } if (MergeState.FieldInfos.HasNorms()) { if (MergeState.InfoStream.IsEnabled("SM")) { t0 = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; } MergeNorms(segmentWriteState); if (MergeState.InfoStream.IsEnabled("SM")) { long t1 = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; MergeState.InfoStream.Message("SM", ((t1 - t0) / 1000000) + " msec to merge norms [" + numMerged + " docs]"); } } if (MergeState.FieldInfos.HasVectors()) { if (MergeState.InfoStream.IsEnabled("SM")) { t0 = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; } numMerged = MergeVectors(); if (MergeState.InfoStream.IsEnabled("SM")) { long t1 = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; MergeState.InfoStream.Message("SM", ((t1 - t0) / 1000000) + " msec to merge vectors [" + numMerged + " docs]"); } Debug.Assert(numMerged == MergeState.SegmentInfo.DocCount); } // write the merged infos FieldInfosWriter fieldInfosWriter = Codec.FieldInfosFormat().FieldInfosWriter; fieldInfosWriter.Write(Directory, MergeState.SegmentInfo.Name, "", MergeState.FieldInfos, Context); return MergeState; } private void MergeDocValues(SegmentWriteState segmentWriteState) { DocValuesConsumer consumer = Codec.DocValuesFormat().FieldsConsumer(segmentWriteState); bool success = false; try { foreach (FieldInfo field in MergeState.FieldInfos) { DocValuesType_e? type = field.DocValuesType; if (type != null) { if (type == DocValuesType_e.NUMERIC) { IList<NumericDocValues> toMerge = new List<NumericDocValues>(); IList<Bits> docsWithField = new List<Bits>(); foreach (AtomicReader reader in MergeState.Readers) { NumericDocValues values = reader.GetNumericDocValues(field.Name); Bits bits = reader.GetDocsWithField(field.Name); if (values == null) { values = DocValues.EMPTY_NUMERIC; bits = new Lucene.Net.Util.Bits_MatchNoBits(reader.MaxDoc); } toMerge.Add(values); docsWithField.Add(bits); } consumer.MergeNumericField(field, MergeState, toMerge, docsWithField); } else if (type == DocValuesType_e.BINARY) { IList<BinaryDocValues> toMerge = new List<BinaryDocValues>(); IList<Bits> docsWithField = new List<Bits>(); foreach (AtomicReader reader in MergeState.Readers) { BinaryDocValues values = reader.GetBinaryDocValues(field.Name); Bits bits = reader.GetDocsWithField(field.Name); if (values == null) { values = DocValues.EMPTY_BINARY; bits = new Lucene.Net.Util.Bits_MatchNoBits(reader.MaxDoc); } toMerge.Add(values); docsWithField.Add(bits); } consumer.MergeBinaryField(field, MergeState, toMerge, docsWithField); } else if (type == DocValuesType_e.SORTED) { IList<SortedDocValues> toMerge = new List<SortedDocValues>(); foreach (AtomicReader reader in MergeState.Readers) { SortedDocValues values = reader.GetSortedDocValues(field.Name); if (values == null) { values = DocValues.EMPTY_SORTED; } toMerge.Add(values); } consumer.MergeSortedField(field, MergeState, toMerge); } else if (type == DocValuesType_e.SORTED_SET) { IList<SortedSetDocValues> toMerge = new List<SortedSetDocValues>(); foreach (AtomicReader reader in MergeState.Readers) { SortedSetDocValues values = reader.GetSortedSetDocValues(field.Name); if (values == null) { values = DocValues.EMPTY_SORTED_SET; } toMerge.Add(values); } consumer.MergeSortedSetField(field, MergeState, toMerge); } else { throw new InvalidOperationException("type=" + type); } } } success = true; } finally { if (success) { IOUtils.Close(consumer); } else { IOUtils.CloseWhileHandlingException(consumer); } } } private void MergeNorms(SegmentWriteState segmentWriteState) { DocValuesConsumer consumer = Codec.NormsFormat().NormsConsumer(segmentWriteState); bool success = false; try { foreach (FieldInfo field in MergeState.FieldInfos) { if (field.HasNorms()) { IList<NumericDocValues> toMerge = new List<NumericDocValues>(); IList<Bits> docsWithField = new List<Bits>(); foreach (AtomicReader reader in MergeState.Readers) { NumericDocValues norms = reader.GetNormValues(field.Name); if (norms == null) { norms = DocValues.EMPTY_NUMERIC; } toMerge.Add(norms); docsWithField.Add(new Lucene.Net.Util.Bits_MatchAllBits(reader.MaxDoc)); } consumer.MergeNumericField(field, MergeState, toMerge, docsWithField); } } success = true; } finally { if (success) { IOUtils.Close(consumer); } else { IOUtils.CloseWhileHandlingException(consumer); } } } private void SetMatchingSegmentReaders() { // If the i'th reader is a SegmentReader and has // identical fieldName -> number mapping, then this // array will be non-null at position i: int numReaders = MergeState.Readers.Count; MergeState.MatchingSegmentReaders = new SegmentReader[numReaders]; // If this reader is a SegmentReader, and all of its // field name -> number mappings match the "merged" // FieldInfos, then we can do a bulk copy of the // stored fields: for (int i = 0; i < numReaders; i++) { AtomicReader reader = MergeState.Readers[i]; // TODO: we may be able to broaden this to // non-SegmentReaders, since FieldInfos is now // required? But... this'd also require exposing // bulk-copy (TVs and stored fields) API in foreign // readers.. if (reader is SegmentReader) { SegmentReader segmentReader = (SegmentReader)reader; bool same = true; FieldInfos segmentFieldInfos = segmentReader.FieldInfos; foreach (FieldInfo fi in segmentFieldInfos) { FieldInfo other = MergeState.FieldInfos.FieldInfo(fi.Number); if (other == null || !other.Name.Equals(fi.Name)) { same = false; break; } } if (same) { MergeState.MatchingSegmentReaders[i] = segmentReader; MergeState.MatchedCount++; } } } if (MergeState.InfoStream.IsEnabled("SM")) { MergeState.InfoStream.Message("SM", "merge store matchedCount=" + MergeState.MatchedCount + " vs " + MergeState.Readers.Count); if (MergeState.MatchedCount != MergeState.Readers.Count) { MergeState.InfoStream.Message("SM", "" + (MergeState.Readers.Count - MergeState.MatchedCount) + " non-bulk merges"); } } } public void MergeFieldInfos() { foreach (AtomicReader reader in MergeState.Readers) { FieldInfos readerFieldInfos = reader.FieldInfos; foreach (FieldInfo fi in readerFieldInfos) { FieldInfosBuilder.Add(fi); } } MergeState.FieldInfos = FieldInfosBuilder.Finish(); } /// /// <returns> The number of documents in all of the readers </returns> /// <exception cref="CorruptIndexException"> if the index is corrupt </exception> /// <exception cref="IOException"> if there is a low-level IO error </exception> private int MergeFields() { StoredFieldsWriter fieldsWriter = Codec.StoredFieldsFormat().FieldsWriter(Directory, MergeState.SegmentInfo, Context); try { return fieldsWriter.Merge(MergeState); } finally { fieldsWriter.Dispose(); } } /// <summary> /// Merge the TermVectors from each of the segments into the new one. </summary> /// <exception cref="IOException"> if there is a low-level IO error </exception> private int MergeVectors() { TermVectorsWriter termVectorsWriter = Codec.TermVectorsFormat().VectorsWriter(Directory, MergeState.SegmentInfo, Context); try { return termVectorsWriter.Merge(MergeState); } finally { termVectorsWriter.Dispose(); } } // NOTE: removes any "all deleted" readers from mergeState.readers private int SetDocMaps() { int numReaders = MergeState.Readers.Count; // Remap docIDs MergeState.DocMaps = new MergeState.DocMap[numReaders]; MergeState.DocBase = new int[numReaders]; int docBase = 0; int i = 0; while (i < MergeState.Readers.Count) { AtomicReader reader = MergeState.Readers[i]; MergeState.DocBase[i] = docBase; MergeState.DocMap docMap = MergeState.DocMap.Build(reader); MergeState.DocMaps[i] = docMap; docBase += docMap.NumDocs; i++; } return docBase; } private void MergeTerms(SegmentWriteState segmentWriteState) { IList<Fields> fields = new List<Fields>(); IList<ReaderSlice> slices = new List<ReaderSlice>(); int docBase = 0; for (int readerIndex = 0; readerIndex < MergeState.Readers.Count; readerIndex++) { AtomicReader reader = MergeState.Readers[readerIndex]; Fields f = reader.Fields; int maxDoc = reader.MaxDoc; if (f != null) { slices.Add(new ReaderSlice(docBase, maxDoc, readerIndex)); fields.Add(f); } docBase += maxDoc; } FieldsConsumer consumer = Codec.PostingsFormat().FieldsConsumer(segmentWriteState); bool success = false; try { consumer.Merge(MergeState, new MultiFields(fields.ToArray(/*Fields.EMPTY_ARRAY*/), slices.ToArray(/*ReaderSlice.EMPTY_ARRAY*/))); success = true; } finally { if (success) { IOUtils.Close(consumer); } else { IOUtils.CloseWhileHandlingException(consumer); } } } } }
using System; using System.Collections.Generic; using System.Linq; using com.tinylabproductions.TLPLib.Extensions; using com.tinylabproductions.TLPLib.Logger; using GenerationAttributes; using JetBrains.Annotations; using tlplib.concurrent; using tlplib.exts; using tlplib.functional; using tlplib.log; using UnityEngine; namespace com.tinylabproductions.TLPLib.debug { /// <summary> /// Exposes fields of objects to Unity window. /// /// <see cref="StateExposerExts"/> and <see cref="StateExposerExts.exposeAllToInspector{A}"/> /// </summary> [Singleton, PublicAPI] public partial class StateExposer { public readonly Scope rootScope = new(); /// <summary>Cleans everything before starting the game.</summary> [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)] static void reset() => instance.rootScope.clearNonStatics(); public Scope withScope(ScopeKey name) => rootScope.withScope(name); public static Scope operator /(StateExposer e, ScopeKey name) => e.withScope(name); [PublicAPI, Record] public sealed partial class ScopeKey { public readonly string name; public readonly Option<UnityEngine.Object> unityObject; /// <summary>Is this scope still valid?</summary> public bool isValid => unityObject.fold(true, obj => obj); public static ScopeKey fromString(string name) => new ScopeKey(name, unityObject: None._); public static implicit operator ScopeKey(string name) => fromString(name); public static ScopeKey fromUnityObject(UnityEngine.Object obj) => new ScopeKey( Log.d.isDebug() && obj is GameObject go ? go.transform.debugPath() : obj.name, unityObject: Some.a(obj) ); public static implicit operator ScopeKey(UnityEngine.Object obj) => fromUnityObject(obj); } [PublicAPI] public sealed class Scope { readonly Dictionary<ScopeKey, Scope> _scopes = new(); readonly List<IData> data = new(); public void add(IData data) => this.data.Add(data); /// <summary>Clear all non statically accessible registered values.</summary> public void clearNonStatics() { lock (this) { var invalidKeys = new HashSet<ScopeKey>(); foreach (var (key, scope) in _scopes) { if (key.isValid) scope.clearNonStatics(); else invalidKeys.Add(key); } foreach (var invalidKey in invalidKeys) { _scopes.Remove(invalidKey); } data.removeWhere(_ => !_.isStatic); } } public KeyValuePair<ScopeKey, Scope>[] scopes { get { // Copy the scopes on access to ensure the locking. lock (this) return _scopes.ToArray(); } } public IEnumerable<IGrouping<Option<object>, ForRepresentation>> groupedData => data.collect(_ => _.representation).GroupBy(_ => _.objectReference); public Scope withScope(ScopeKey name) { // Lock to support accessing from all threads. lock (this) { return _scopes.getOrUpdate(name, () => new()); } } public static Scope operator /(Scope e, ScopeKey name) => e.withScope(name); /// <summary>Exposes a named value that is available statically (not via an object instance).</summary> public void exposeStatic(string name, Func<IRenderableValue> get) => add(new StaticData(name, get)); public void exposeStatic(string name, Func<string> get) => exposeStatic(name, () => new StringValue(get())); public void exposeStatic(string name, Func<float> get) => exposeStatic(name, () => new FloatValue(get())); public void exposeStatic(string name, Func<bool> get) => exposeStatic(name, () => new BoolValue(get())); public void exposeStatic(string name, Func<UnityEngine.Object> get) => exposeStatic(name, () => new ObjectValue(get())); public void exposeStatic(string name, Func<Action> onClick) => exposeStatic(name, () => new ActionValue(onClick())); /// <summary>Helper for exposing <see cref="Future{A}"/>.</summary> public void exposeStatic<A>(string name, Func<Future<A>> get) => exposeStatic(name, () => get().ToString()); /// <summary>Exposes a named value that is available via an object instance.</summary> public void expose<A>(A reference, string name, Func<A, IRenderableValue> get) where A : class => add(new InstanceData<A>(reference.weakRef(), name, get)); /// <summary> /// Helper for exposing <see cref="Future{A}"/>. Does not do anything if the future is not async (because it's a /// struct then). /// </summary> public void expose<A>(Future<A> future, string name) { if (future.asHeapFuture.valueOut(out var heapFuture)) expose(heapFuture, name, _ => _.ToString()); } } public interface IData { /// <summary>Does this data represent statically accessible values?</summary> bool isStatic { get; } Option<ForRepresentation> representation { get; } } /// <summary>Value that is available an object instance.</summary> [Record] partial class InstanceData<A> : IData where A : class { readonly WeakReference<A> reference; readonly string name; readonly Func<A, IRenderableValue> get; public bool isStatic => false; public Option<ForRepresentation> representation => reference.TryGetTarget(out var _ref) ? Some.a(new ForRepresentation(Some.a<object>(_ref), name, get(_ref))) : None._; } /// <summary>Value that is available statically.</summary> [Record] partial class StaticData : IData { readonly string name; readonly Func<IRenderableValue> get; public bool isStatic => true; public Option<ForRepresentation> representation => Some.a(new ForRepresentation(None._, name, get())); } /// <summary>Allows you to represent a runtime value.</summary> [Record] public readonly partial struct ForRepresentation { /// <summary>None if this value is available statically.</summary> public readonly Option<object> objectReference; public readonly string name; public readonly IRenderableValue value; } /// <summary>Represents a value that we can render.</summary> [Matcher] public abstract class IRenderableValue { public static implicit operator IRenderableValue(string v) => new StringValue(v); public static implicit operator IRenderableValue(float v) => new FloatValue(v); public static implicit operator IRenderableValue(double v) => new FloatValue((float) v); public static implicit operator IRenderableValue(bool v) => new BoolValue(v); public static implicit operator IRenderableValue(UnityEngine.Object v) => new ObjectValue(v); public static implicit operator IRenderableValue(Action v) => new ActionValue(v); public static implicit operator IRenderableValue(IRenderableValue[] v) => new EnumerableValue(v); } [Record] public sealed partial class StringValue : IRenderableValue { public readonly string value; } [Record] public sealed partial class FloatValue : IRenderableValue { public readonly float value; } [Record] public sealed partial class BoolValue : IRenderableValue { public readonly bool value; } [Record] public sealed partial class ObjectValue : IRenderableValue { public readonly UnityEngine.Object value; } [Record] public sealed partial class ActionValue : IRenderableValue { public readonly string label; public readonly Action value; public ActionValue(Action value) : this("Run", value) {} } /// <summary>Renders the key in column 1 and value in column 2.</summary> [Record] public sealed partial class KVValue : IRenderableValue { public readonly IRenderableValue key, value; } /// <summary>Renders a header and then the value, but indents the value by the specified indent.</summary> [Record] public sealed partial class HeaderValue : IRenderableValue { public readonly IRenderableValue header, value; public readonly byte indentBy; public HeaderValue(IRenderableValue header, IRenderableValue value) : this(header, value, 1) {} } /// <summary>Renders given values with header stating the count and separator between values.</summary> [Record] public sealed partial class EnumerableValue : IRenderableValue { /// <summary>Should we render the element count?</summary> public readonly bool showCount; public readonly IReadOnlyCollection<IRenderableValue> values; public EnumerableValue(IReadOnlyCollection<IRenderableValue> values) : this(showCount: true, values) {} } } [PublicAPI] public static class StateExposerExts { public static void exposeToInspector<A>( this GameObject go, A reference, string name, Func<A, StateExposer.IRenderableValue> get ) where A : class { (StateExposer.instance / go).expose(reference, name, get); } public static void exposeAllToInspector<A>( this GameObject go, A reference ) where A : class { foreach (var field in typeof(A).getAllFields()) { var fieldType = field.FieldType; if (fieldType.IsSubclassOf(typeof(float))) exposeToInspector(go, reference, field.Name, a => (float) field.GetValue(a)); else if (fieldType.IsSubclassOf(typeof(bool))) exposeToInspector(go, reference, field.Name, a => (bool) field.GetValue(a)); else if (fieldType.IsSubclassOf(typeof(UnityEngine.Object))) exposeToInspector(go, reference, field.Name, a => (UnityEngine.Object) field.GetValue(a)); else exposeToInspector(go, reference, field.Name, a => { var obj = field.GetValue(a); return obj == null ? "null" : obj.ToString(); }); } } } }
////////////////////////////////////////////////////////////////////////////////////// // Author : Shukri Adams // // Contact : shukri.adams@gmail.com // // // // vcFramework : A reuseable library of utility classes // // Copyright (C) // ////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Xml; using vcFramework.Serialization; namespace vcFramework.Xml { /// <summary> /// Stores and retrieves values in an xml file. /// </summary> public class StateHolder { #region MEMBERS /// <summary> /// Xml document which this class stores its data in /// </summary> private XmlDocument _dataHolder; /// <summary> /// Local drive path for xml document - must be passed in as construcotr argument /// </summary> private string _documentPath; #endregion #region PROPERTIES /// <summary> /// If true, state data will be saved to file each time state is changed. This /// can be expensive if there is a lot of state data, but removes the need to /// explicityl save state data from the client code /// </summary> public bool SaveOnTheFly { get;set;} #endregion #region CONSTRUCTORS /// <summary> /// Default Constructor /// </summary> /// <param name="documentPath"></param> public StateHolder(string documentPath) { _documentPath = documentPath; // sets up xml document on which this object is based CreateXmlBase(); // sets default this.SaveOnTheFly = true; } #endregion #region METHODS /// <summary> /// loads or creates Xmldocument in which state data is stored /// </summary> private void CreateXmlBase() { _dataHolder = new XmlDocument(); if (File.Exists(_documentPath)) { _dataHolder.Load(_documentPath); } else { _dataHolder.InnerXml = "<!-- This is an autogenerated file - do not modify it --><StateItems/>"; _dataHolder.Save(_documentPath); } } /// <summary> /// Stores an xml node udner the given name /// </summary> /// <param name="key"></param> /// <param name="item"></param> public void Add(string key, object item) { if (_dataHolder == null || _dataHolder.DocumentElement == null) throw new Exception("State document is null or has invalid content."); // ########################################### // removes item at named position if that // item already exists // ------------------------------------------- Remove(key); // ########################################### // adds new item // ------------------------------------------- string serialized = SerializeLib.SerializeToXmlString(item); XmlDocumentFragment fragment = _dataHolder.CreateDocumentFragment(); fragment.InnerXml = string.Format("<StateItem UniqueNameKey='{0}'>{1}</StateItem>", key, serialized); _dataHolder.DocumentElement.AppendChild(fragment); if (SaveOnTheFly) this.Save(); } /// <summary> /// Retrieves an xml node stored under the given name /// </summary> /// <param name="key"></param> /// <returns></returns> public object Retrieve(string key) { if (_dataHolder == null || _dataHolder.DocumentElement == null) throw new Exception("State document is null or has invalid content."); XmlNode node = null; string path = string.Format(".//StateItem [@UniqueNameKey='{0}']", key); if (_dataHolder.DocumentElement.SelectSingleNode(path) != null) node = _dataHolder.DocumentElement.SelectSingleNode(path).FirstChild; return SerializeLib.DeserializeFromXmlString(node.OuterXml); } /// <summary> /// Removes the given item if it exists. Returns true if the item was removed /// </summary> /// <param name="key"></param> public bool Remove(string key) { if (_dataHolder == null || _dataHolder.DocumentElement == null) throw new Exception("State document is null or has invalid content."); XmlNode node = _dataHolder.DocumentElement.SelectSingleNode(string.Format(".//StateItem [@UniqueNameKey='{0}']", key)); if (node == null) return false; _dataHolder.DocumentElement.RemoveChild(node); return true; } /// <summary> /// returns true if underlying xml storage document contains the item with the given name. /// </summary> /// <param name="key"></param> /// <returns></returns> public bool Contains(string key) { if (_dataHolder == null || _dataHolder.DocumentElement == null) throw new Exception("State document is null or has invalid content."); if (_dataHolder.DocumentElement.SelectSingleNode(string.Format(".//StateItem [@UniqueNameKey='{0}']", key)) != null) return true; return false; } /// <summary> /// Saves object state to disk /// </summary> public void Save() { _dataHolder.Save(_documentPath); } /// <summary> /// Forceabily recreates the Xml base document for this objec /// </summary> public void ForceReload() { CreateXmlBase(); } /// <summary> /// Deletes all state data /// </summary> public void Clear() { if (_dataHolder == null || _dataHolder.DocumentElement == null) throw new Exception("State document is null or has invalid content."); while (_dataHolder.DocumentElement.ChildNodes.Count > 0) _dataHolder.DocumentElement.RemoveChild( _dataHolder.DocumentElement.ChildNodes[0]); if (SaveOnTheFly) this.Save(); } #endregion } }
namespace FakeItEasy.Specs { using System; using System.Collections.Generic; using System.Linq; using FakeItEasy.Core; using FluentAssertions; using Xbehave; public static class FakeSpecs { public interface IFoo { void AMethod(); void AnotherMethod(); void AnotherMethod(string text); object AMethodReturningAnObject(); } [Scenario] public static void NonGenericCallsSuccess( IFoo fake, IEnumerable<ICompletedFakeObjectCall> completedCalls) { "Given a Fake" .x(() => fake = A.Fake<IFoo>()); "And I make several calls to the Fake" .x(() => { fake.AMethod(); fake.AnotherMethod(); fake.AnotherMethod("houseboat"); }); "When I use the static Fake class to get the calls made on the Fake" .x(() => completedCalls = Fake.GetCalls(fake)); "Then the calls made to the Fake will be returned" .x(() => completedCalls.Select(call => call.Method.Name) .Should() .Equal("AMethod", "AnotherMethod", "AnotherMethod")); } [Scenario] public static void MatchingCallsWithNoMatches( IFoo fake, IEnumerable<ICompletedFakeObjectCall> completedCalls, IEnumerable<ICompletedFakeObjectCall> matchedCalls) { "Given a Fake" .x(() => fake = A.Fake<IFoo>()); "And I make several calls to the Fake" .x(() => { fake.AMethod(); fake.AnotherMethod("houseboat"); }); "And I use the static Fake class to get the calls made on the Fake" .x(() => completedCalls = Fake.GetCalls(fake)); "When I use Matching to find calls to a method with no matches" .x(() => matchedCalls = completedCalls.Matching<IFoo>(c => c.AnotherMethod("hovercraft"))); "Then it finds no calls" .x(() => matchedCalls.Should().BeEmpty()); } [Scenario] public static void MatchingCallsWithMatches( IFoo fake, IEnumerable<ICompletedFakeObjectCall> completedCalls, IEnumerable<ICompletedFakeObjectCall> matchedCalls) { "Given a Fake" .x(() => fake = A.Fake<IFoo>()); "And I make several calls to the Fake" .x(() => { fake.AMethod(); fake.AnotherMethod(); fake.AnotherMethod("houseboat"); }); "And I use the static Fake class to get the calls made on the Fake" .x(() => completedCalls = Fake.GetCalls(fake)); "When I use Matching to find calls to a method with a match" .x(() => matchedCalls = completedCalls.Matching<IFoo>(c => c.AnotherMethod("houseboat"))); "Then it finds the matching call" .x(() => matchedCalls.Select(c => c.Method.Name).Should().Equal("AnotherMethod")); } [Scenario] public static void ClearRecordedCalls(IFoo fake) { "Given a Fake" .x(() => fake = A.Fake<IFoo>()); "And I make several calls to the Fake" .x(() => { fake.AMethod(); fake.AnotherMethod(); fake.AnotherMethod("houseboat"); }); "When I clear the recorded calls" .x(() => Fake.ClearRecordedCalls(fake)); "Then the recorded call list is empty" .x(() => Fake.GetCalls(fake).Should().BeEmpty()); } [Scenario] public static void ClearConfiguration(IFoo fake, bool configuredBehaviorWasUsed) { "Given a Fake" .x(() => fake = A.Fake<IFoo>()); "And I configure a method call on the Fake" .x(() => A.CallTo(() => fake.AMethod()).Invokes(() => configuredBehaviorWasUsed = true)); "When I clear the configuration" .x(() => Fake.ClearConfiguration(fake)); "And I execute the previously-configured method" .x(() => fake.AMethod()); "Then previously-configured behavior is not executed" .x(() => configuredBehaviorWasUsed.Should().BeFalse()); } [Scenario] public static void RecordedCallHasReturnValue( IFoo fake, object returnValue, ICompletedFakeObjectCall recordedCall) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "When I call a method on the fake" .x(() => returnValue = fake.AMethodReturningAnObject()); "And I retrieve the call from the recorded calls" .x(() => recordedCall = Fake.GetCalls(fake).Single()); "Then the recorded call's return value should be the value that was actually returned" .x(() => recordedCall.ReturnValue.Should().Be(returnValue)); } [Scenario] public static void RecordedDelegateCallHasReturnValue( Func<object> fake, object returnValue, ICompletedFakeObjectCall recordedCall) { "Given a fake delegate" .x(() => fake = A.Fake<Func<object>>()); "When I invoke the fake delegate" .x(() => returnValue = fake()); "And I retrieve the call from the recorded calls" .x(() => recordedCall = Fake.GetCalls(fake).Single()); "Then the recorded call's return value should be the value that was actually returned" .x(() => recordedCall.ReturnValue.Should().Be(returnValue)); } [Scenario] public static void TryGetFakeManagerWhenFakeObject(object fake, bool result, FakeManager? manager) { "Given a fake object" .x(() => fake = A.Fake<object>()); "When I try to get the FakeManager for that object" .x(() => result = Fake.TryGetFakeManager(fake, out manager)); "Then the result should be true" .x(() => result.Should().BeTrue()); "And manager should be set" .x(() => manager.Should().NotBeNull()); } [Scenario] public static void TryGetFakeManagerWhenNonFakeObject(object notFake, bool result, FakeManager? manager) { "Given a non-fake object" .x(() => notFake = new object()); "When I try to get the FakeManager for that object" .x(() => result = Fake.TryGetFakeManager(notFake, out manager)); "Then the result should be false" .x(() => result.Should().BeFalse()); "And manager should be null" .x(() => manager.Should().BeNull()); } [Scenario] public static void FakeIsFake(object fake, bool result) { "Given a fake object" .x(() => fake = A.Fake<object>()); "When I check if that object is fake" .x(() => result = Fake.IsFake(fake)); "Then the result should be true" .x(() => result.Should().BeTrue()); } [Scenario] public static void NonFakeIsIsNotFake(object fake, bool result) { "Given a non-fake object" .x(() => fake = new object()); "When I check if that object is fake" .x(() => result = Fake.IsFake(fake)); "Then the result should be false" .x(() => result.Should().BeFalse()); } } }
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // 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 Castle.Facilities.WcfIntegration.Async.TypeSystem { using System; #if DOTNET40 using System.Collections.Concurrent; #endif using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Description; using Castle.Facilities.WcfIntegration.Internal; [Serializable] public class AsyncType : TypeDelegator, ISerializable { private Type[] interfaces; private readonly Type syncType; private readonly Dictionary<RuntimeMethodHandle, MethodInfo> beginMethods; private readonly Dictionary<RuntimeMethodHandle, MethodInfo> endMethods; private readonly Dictionary<RuntimeMethodHandle, BeginMethod> fakeBeginMethods; private readonly Dictionary<RuntimeMethodHandle, EndMethod> fakeEndMethods; private BeginMethod lastAccessedBeginMethod; private static readonly ConcurrentDictionary<Type, AsyncType> typeToAsyncType = new ConcurrentDictionary<Type, AsyncType>(); private AsyncType(Type type) : base(type) { if (type == null) { throw new ArgumentNullException("type"); } if (type.IsInterface == false) { throw new ArgumentException("Interface type expected.", "type"); } syncType = type; beginMethods = new Dictionary<RuntimeMethodHandle, MethodInfo>(); endMethods = new Dictionary<RuntimeMethodHandle, MethodInfo>(); fakeBeginMethods = new Dictionary<RuntimeMethodHandle, BeginMethod>(); fakeEndMethods = new Dictionary<RuntimeMethodHandle, EndMethod>(); CollectAsynchronousMethods(); } protected AsyncType(SerializationInfo info, StreamingContext context) : this(GetBaseType(info)) { } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("syncType", syncType.AssemblyQualifiedName); } public Type SyncType { get { return syncType; } } public override bool IsDefined(Type attributeType, bool inherit) { //TODO: review this piece if it needs some magic too return base.IsDefined(attributeType, inherit); } public override Type[] GetInterfaces() { return WcfUtils.SafeInitialize(ref interfaces, () => { var effectiveInterfaces = syncType.GetInterfaces(); for (int i = 0; i < effectiveInterfaces.Length; ++i) { effectiveInterfaces[i] = GetEffectiveType(effectiveInterfaces[i]); } return effectiveInterfaces; }); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { var methods = syncType.GetMethods(bindingAttr); return methods.Concat(fakeBeginMethods.Values.Cast<MethodInfo>()) .Concat(fakeEndMethods.Values.Cast<MethodInfo>()).ToArray(); } public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { var baseResult = syncType.GetMember(name, bindingAttr); if ((type & MemberTypes.Method) != MemberTypes.Method) { return baseResult; } //NOTE: since WCF only uses this method for looking up end methods we try to match only end methods as well if (!name.StartsWith("End", StringComparison.Ordinal)) { return baseResult; } string potentialSyncMethodName = name.Substring("End".Length); if (IsMatchingEndMethodForLastAccessedBeginMethod(potentialSyncMethodName)) { return new MemberInfo[] {fakeEndMethods[lastAccessedBeginMethod.SyncMethod.MethodHandle]}; } return baseResult.Union(fakeEndMethods.Values.Where(m => m.SyncMethod.Name.Equals(potentialSyncMethodName, StringComparison.Ordinal) ).Cast<MemberInfo>()).ToArray(); } private bool IsMatchingEndMethodForLastAccessedBeginMethod(string potentialSyncMethodName) { return lastAccessedBeginMethod != null && lastAccessedBeginMethod.SyncMethod.Name.Equals(potentialSyncMethodName, StringComparison.Ordinal); } public MethodInfo GetBeginMethod(MethodInfo syncMethod) { if (syncMethod.DeclaringType == syncType) { BeginMethod beginMethod; if (fakeBeginMethods.TryGetValue(syncMethod.MethodHandle, out beginMethod)) return beginMethod; return beginMethods[syncMethod.MethodHandle]; } foreach (var asyncType in GetInterfaces().OfType<AsyncType>() .Where(i => i.SyncType == syncMethod.DeclaringType)) { BeginMethod beginMethod; if (asyncType.fakeBeginMethods.TryGetValue(syncMethod.MethodHandle, out beginMethod)) return beginMethod; return asyncType.beginMethods[syncMethod.MethodHandle]; } return null; } public void PushLastAccessedBeginMethod(BeginMethod beginMethod) { lastAccessedBeginMethod = beginMethod; } public MethodInfo GetEndMethod(MethodInfo syncMethod) { if (syncMethod.DeclaringType == syncType) { EndMethod endMethod; if (fakeEndMethods.TryGetValue(syncMethod.MethodHandle, out endMethod)) return endMethod; return endMethods[syncMethod.MethodHandle]; } foreach (var asyncType in GetInterfaces().OfType<AsyncType>() .Where(i => i.SyncType == syncMethod.DeclaringType)) { EndMethod endMethod; if (asyncType.fakeEndMethods.TryGetValue(syncMethod.MethodHandle, out endMethod)) return endMethod; return asyncType.endMethods[syncMethod.MethodHandle]; } return null; } public static AsyncType GetAsyncType<T>() { return GetAsyncType(typeof(T)); } public static AsyncType GetAsyncType(Type type) { return typeToAsyncType.GetOrAdd(type, addType => new AsyncType(type)); } private void CollectAsynchronousMethods() { var contract = ContractDescription.GetContract(syncType); foreach (var operation in contract.Operations) { var syncMethod = operation.SyncMethod; if (syncMethod != null && syncMethod.DeclaringType == syncType) { if (operation.BeginMethod == null) { fakeBeginMethods.Add(syncMethod.MethodHandle, new BeginMethod(syncMethod, this)); fakeEndMethods.Add(syncMethod.MethodHandle, new EndMethod(syncMethod, this)); } else { beginMethods.Add(syncMethod.MethodHandle, operation.BeginMethod); endMethods.Add(syncMethod.MethodHandle, operation.EndMethod); } } } } private static Type GetEffectiveType(Type asyncCandidateType) { if (asyncCandidateType != null && asyncCandidateType != typeof(object)) { var serviceContract = asyncCandidateType.GetAttribute<ServiceContractAttribute>(false); if (serviceContract != null) { return GetAsyncType(asyncCandidateType); } } return asyncCandidateType; } private static Type GetBaseType(SerializationInfo information) { string typeName = information.GetString("syncType"); return GetType(typeName); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sdb-2009-04-15.normal.json service model. */ using System; using System.Collections.Generic; using Amazon.SimpleDB.Model; using Amazon.SimpleDB.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.SimpleDB { /// <summary> /// Implementation for accessing SimpleDB /// /// Amazon SimpleDB is a web service providing the core database functions of data indexing /// and querying in the cloud. By offloading the time and effort associated with building /// and operating a web-scale database, SimpleDB provides developers the freedom to focus /// on application development. /// <para> /// A traditional, clustered relational database requires a sizable upfront capital outlay, /// is complex to design, and often requires extensive and repetitive database administration. /// Amazon SimpleDB is dramatically simpler, requiring no schema, automatically indexing /// your data and providing a simple API for storage and access. This approach eliminates /// the administrative burden of data modeling, index maintenance, and performance tuning. /// Developers gain access to this functionality within Amazon's proven computing environment, /// are able to scale instantly, and pay only for what they use. /// </para> /// /// <para> /// Visit <a href="http://aws.amazon.com/simpledb/">http://aws.amazon.com/simpledb/</a> /// for more information. /// </para> /// </summary> public partial class AmazonSimpleDBClient : AmazonServiceClient, IAmazonSimpleDB { #region Constructors /// <summary> /// Constructs AmazonSimpleDBClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonSimpleDBClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonSimpleDBConfig()) { } /// <summary> /// Constructs AmazonSimpleDBClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonSimpleDBClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonSimpleDBConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonSimpleDBClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonSimpleDBClient Configuration Object</param> public AmazonSimpleDBClient(AmazonSimpleDBConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonSimpleDBClient(AWSCredentials credentials) : this(credentials, new AmazonSimpleDBConfig()) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonSimpleDBClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonSimpleDBConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Credentials and an /// AmazonSimpleDBClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonSimpleDBClient Configuration Object</param> public AmazonSimpleDBClient(AWSCredentials credentials, AmazonSimpleDBConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonSimpleDBConfig()) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonSimpleDBConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID, AWS Secret Key and an /// AmazonSimpleDBClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonSimpleDBClient Configuration Object</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonSimpleDBConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSimpleDBConfig()) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSimpleDBConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID, AWS Secret Key and an /// AmazonSimpleDBClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonSimpleDBClient Configuration Object</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonSimpleDBConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new QueryStringSigner(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region BatchDeleteAttributes /// <summary> /// Performs multiple DeleteAttributes operations in a single call, which reduces round /// trips and latencies. This enables Amazon SimpleDB to optimize requests, which generally /// yields better throughput. /// /// /// <para> /// The following limitations are enforced for this operation: <ul> <li>1 MB request /// size</li> <li>25 item limit per BatchDeleteAttributes operation</li> </ul> /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchDeleteAttributes service method.</param> /// /// <returns>The response from the BatchDeleteAttributes service method, as returned by SimpleDB.</returns> public BatchDeleteAttributesResponse BatchDeleteAttributes(BatchDeleteAttributesRequest request) { var marshaller = new BatchDeleteAttributesRequestMarshaller(); var unmarshaller = BatchDeleteAttributesResponseUnmarshaller.Instance; return Invoke<BatchDeleteAttributesRequest,BatchDeleteAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the BatchDeleteAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the BatchDeleteAttributes operation on AmazonSimpleDBClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndBatchDeleteAttributes /// operation.</returns> public IAsyncResult BeginBatchDeleteAttributes(BatchDeleteAttributesRequest request, AsyncCallback callback, object state) { var marshaller = new BatchDeleteAttributesRequestMarshaller(); var unmarshaller = BatchDeleteAttributesResponseUnmarshaller.Instance; return BeginInvoke<BatchDeleteAttributesRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the BatchDeleteAttributes operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginBatchDeleteAttributes.</param> /// /// <returns>Returns a BatchDeleteAttributesResult from SimpleDB.</returns> public BatchDeleteAttributesResponse EndBatchDeleteAttributes(IAsyncResult asyncResult) { return EndInvoke<BatchDeleteAttributesResponse>(asyncResult); } #endregion #region BatchPutAttributes /// <summary> /// The <code>BatchPutAttributes</code> operation creates or replaces attributes within /// one or more items. By using this operation, the client can perform multiple <a>PutAttribute</a> /// operation with a single call. This helps yield savings in round trips and latencies, /// enabling Amazon SimpleDB to optimize requests and generally produce better throughput. /// /// /// /// <para> /// The client may specify the item name with the <code>Item.X.ItemName</code> parameter. /// The client may specify new attributes using a combination of the <code>Item.X.Attribute.Y.Name</code> /// and <code>Item.X.Attribute.Y.Value</code> parameters. The client may specify the first /// attribute for the first item using the parameters <code>Item.0.Attribute.0.Name</code> /// and <code>Item.0.Attribute.0.Value</code>, and for the second attribute for the first /// item by the parameters <code>Item.0.Attribute.1.Name</code> and <code>Item.0.Attribute.1.Value</code>, /// and so on. /// </para> /// /// <para> /// Attributes are uniquely identified within an item by their name/value combination. /// For example, a single item can have the attributes <code>{ "first_name", "first_value" /// }</code> and <code>{ "first_name", "second_value" }</code>. However, it cannot have /// two attribute instances where both the <code>Item.X.Attribute.Y.Name</code> and <code>Item.X.Attribute.Y.Value</code> /// are the same. /// </para> /// /// <para> /// Optionally, the requester can supply the <code>Replace</code> parameter for each /// individual value. Setting this value to <code>true</code> will cause the new attribute /// values to replace the existing attribute values. For example, if an item <code>I</code> /// has the attributes <code>{ 'a', '1' }, { 'b', '2'}</code> and <code>{ 'b', '3' }</code> /// and the requester does a BatchPutAttributes of <code>{'I', 'b', '4' }</code> with /// the Replace parameter set to true, the final attributes of the item will be <code>{ /// 'a', '1' }</code> and <code>{ 'b', '4' }</code>, replacing the previous values of /// the 'b' attribute with the new value. /// </para> /// <important> This operation is vulnerable to exceeding the maximum URL size when making /// a REST request using the HTTP GET method. This operation does not support conditions /// using <code>Expected.X.Name</code>, <code>Expected.X.Value</code>, or <code>Expected.X.Exists</code>. /// </important> /// <para> /// You can execute multiple <code>BatchPutAttributes</code> operations and other operations /// in parallel. However, large numbers of concurrent <code>BatchPutAttributes</code> /// calls can result in Service Unavailable (503) responses. /// </para> /// /// <para> /// The following limitations are enforced for this operation: <ul> <li>256 attribute /// name-value pairs per item</li> <li>1 MB request size</li> <li>1 billion attributes /// per domain</li> <li>10 GB of total user data storage per domain</li> <li>25 item limit /// per <code>BatchPutAttributes</code> operation</li> </ul> /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchPutAttributes service method.</param> /// /// <returns>The response from the BatchPutAttributes service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.DuplicateItemNameException"> /// The item name was specified more than once. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberDomainAttributesExceededException"> /// Too many attributes in this domain. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberDomainBytesExceededException"> /// Too many bytes in this domain. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberItemAttributesExceededException"> /// Too many attributes in this item. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberSubmittedAttributesExceededException"> /// Too many attributes exist in a single call. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberSubmittedItemsExceededException"> /// Too many items exist in a single call. /// </exception> public BatchPutAttributesResponse BatchPutAttributes(BatchPutAttributesRequest request) { var marshaller = new BatchPutAttributesRequestMarshaller(); var unmarshaller = BatchPutAttributesResponseUnmarshaller.Instance; return Invoke<BatchPutAttributesRequest,BatchPutAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the BatchPutAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the BatchPutAttributes operation on AmazonSimpleDBClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndBatchPutAttributes /// operation.</returns> public IAsyncResult BeginBatchPutAttributes(BatchPutAttributesRequest request, AsyncCallback callback, object state) { var marshaller = new BatchPutAttributesRequestMarshaller(); var unmarshaller = BatchPutAttributesResponseUnmarshaller.Instance; return BeginInvoke<BatchPutAttributesRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the BatchPutAttributes operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginBatchPutAttributes.</param> /// /// <returns>Returns a BatchPutAttributesResult from SimpleDB.</returns> public BatchPutAttributesResponse EndBatchPutAttributes(IAsyncResult asyncResult) { return EndInvoke<BatchPutAttributesResponse>(asyncResult); } #endregion #region CreateDomain /// <summary> /// The <code>CreateDomain</code> operation creates a new domain. The domain name should /// be unique among the domains associated with the Access Key ID provided in the request. /// The <code>CreateDomain</code> operation may take 10 or more seconds to complete. /// /// /// <para> /// The client can create up to 100 domains per account. /// </para> /// /// <para> /// If the client requires additional domains, go to <a href="http://aws.amazon.com/contact-us/simpledb-limit-request/"> /// http://aws.amazon.com/contact-us/simpledb-limit-request/</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDomain service method.</param> /// /// <returns>The response from the CreateDomain service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberDomainsExceededException"> /// Too many domains exist per this account. /// </exception> public CreateDomainResponse CreateDomain(CreateDomainRequest request) { var marshaller = new CreateDomainRequestMarshaller(); var unmarshaller = CreateDomainResponseUnmarshaller.Instance; return Invoke<CreateDomainRequest,CreateDomainResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateDomain operation on AmazonSimpleDBClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateDomain /// operation.</returns> public IAsyncResult BeginCreateDomain(CreateDomainRequest request, AsyncCallback callback, object state) { var marshaller = new CreateDomainRequestMarshaller(); var unmarshaller = CreateDomainResponseUnmarshaller.Instance; return BeginInvoke<CreateDomainRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateDomain operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateDomain.</param> /// /// <returns>Returns a CreateDomainResult from SimpleDB.</returns> public CreateDomainResponse EndCreateDomain(IAsyncResult asyncResult) { return EndInvoke<CreateDomainResponse>(asyncResult); } #endregion #region DeleteAttributes /// <summary> /// Deletes one or more attributes associated with an item. If all attributes of the /// item are deleted, the item is deleted. /// /// /// <para> /// <code>DeleteAttributes</code> is an idempotent operation; running it multiple times /// on the same item or attribute does not result in an error response. /// </para> /// /// <para> /// Because Amazon SimpleDB makes multiple copies of item data and uses an eventual consistency /// update model, performing a <a>GetAttributes</a> or <a>Select</a> operation (read) /// immediately after a <code>DeleteAttributes</code> or <a>PutAttributes</a> operation /// (write) might not return updated item data. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteAttributes service method.</param> /// /// <returns>The response from the DeleteAttributes service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.AttributeDoesNotExistException"> /// The specified attribute does not exist. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> public DeleteAttributesResponse DeleteAttributes(DeleteAttributesRequest request) { var marshaller = new DeleteAttributesRequestMarshaller(); var unmarshaller = DeleteAttributesResponseUnmarshaller.Instance; return Invoke<DeleteAttributesRequest,DeleteAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteAttributes operation on AmazonSimpleDBClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteAttributes /// operation.</returns> public IAsyncResult BeginDeleteAttributes(DeleteAttributesRequest request, AsyncCallback callback, object state) { var marshaller = new DeleteAttributesRequestMarshaller(); var unmarshaller = DeleteAttributesResponseUnmarshaller.Instance; return BeginInvoke<DeleteAttributesRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteAttributes operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteAttributes.</param> /// /// <returns>Returns a DeleteAttributesResult from SimpleDB.</returns> public DeleteAttributesResponse EndDeleteAttributes(IAsyncResult asyncResult) { return EndInvoke<DeleteAttributesResponse>(asyncResult); } #endregion #region DeleteDomain /// <summary> /// The <code>DeleteDomain</code> operation deletes a domain. Any items (and their attributes) /// in the domain are deleted as well. The <code>DeleteDomain</code> operation might take /// 10 or more seconds to complete. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDomain service method.</param> /// /// <returns>The response from the DeleteDomain service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> public DeleteDomainResponse DeleteDomain(DeleteDomainRequest request) { var marshaller = new DeleteDomainRequestMarshaller(); var unmarshaller = DeleteDomainResponseUnmarshaller.Instance; return Invoke<DeleteDomainRequest,DeleteDomainResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDomain operation on AmazonSimpleDBClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteDomain /// operation.</returns> public IAsyncResult BeginDeleteDomain(DeleteDomainRequest request, AsyncCallback callback, object state) { var marshaller = new DeleteDomainRequestMarshaller(); var unmarshaller = DeleteDomainResponseUnmarshaller.Instance; return BeginInvoke<DeleteDomainRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteDomain operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteDomain.</param> /// /// <returns>Returns a DeleteDomainResult from SimpleDB.</returns> public DeleteDomainResponse EndDeleteDomain(IAsyncResult asyncResult) { return EndInvoke<DeleteDomainResponse>(asyncResult); } #endregion #region DomainMetadata /// <summary> /// Returns information about the domain, including when the domain was created, the /// number of items and attributes in the domain, and the size of the attribute names /// and values. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DomainMetadata service method.</param> /// /// <returns>The response from the DomainMetadata service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> public DomainMetadataResponse DomainMetadata(DomainMetadataRequest request) { var marshaller = new DomainMetadataRequestMarshaller(); var unmarshaller = DomainMetadataResponseUnmarshaller.Instance; return Invoke<DomainMetadataRequest,DomainMetadataResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DomainMetadata operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DomainMetadata operation on AmazonSimpleDBClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDomainMetadata /// operation.</returns> public IAsyncResult BeginDomainMetadata(DomainMetadataRequest request, AsyncCallback callback, object state) { var marshaller = new DomainMetadataRequestMarshaller(); var unmarshaller = DomainMetadataResponseUnmarshaller.Instance; return BeginInvoke<DomainMetadataRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DomainMetadata operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDomainMetadata.</param> /// /// <returns>Returns a DomainMetadataResult from SimpleDB.</returns> public DomainMetadataResponse EndDomainMetadata(IAsyncResult asyncResult) { return EndInvoke<DomainMetadataResponse>(asyncResult); } #endregion #region GetAttributes /// <summary> /// Returns all of the attributes associated with the specified item. Optionally, the /// attributes returned can be limited to one or more attributes by specifying an attribute /// name parameter. /// /// /// <para> /// If the item does not exist on the replica that was accessed for this operation, an /// empty set is returned. The system does not return an error as it cannot guarantee /// the item does not exist on other replicas. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetAttributes service method.</param> /// /// <returns>The response from the GetAttributes service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> public GetAttributesResponse GetAttributes(GetAttributesRequest request) { var marshaller = new GetAttributesRequestMarshaller(); var unmarshaller = GetAttributesResponseUnmarshaller.Instance; return Invoke<GetAttributesRequest,GetAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetAttributes operation on AmazonSimpleDBClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetAttributes /// operation.</returns> public IAsyncResult BeginGetAttributes(GetAttributesRequest request, AsyncCallback callback, object state) { var marshaller = new GetAttributesRequestMarshaller(); var unmarshaller = GetAttributesResponseUnmarshaller.Instance; return BeginInvoke<GetAttributesRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetAttributes operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetAttributes.</param> /// /// <returns>Returns a GetAttributesResult from SimpleDB.</returns> public GetAttributesResponse EndGetAttributes(IAsyncResult asyncResult) { return EndInvoke<GetAttributesResponse>(asyncResult); } #endregion #region ListDomains /// <summary> /// The <code>ListDomains</code> operation lists all domains associated with the Access /// Key ID. It returns domain names up to the limit set by <a href="#MaxNumberOfDomains">MaxNumberOfDomains</a>. /// A <a href="#NextToken">NextToken</a> is returned if there are more than <code>MaxNumberOfDomains</code> /// domains. Calling <code>ListDomains</code> successive times with the <code>NextToken</code> /// provided by the operation returns up to <code>MaxNumberOfDomains</code> more domain /// names with each successive operation call. /// </summary> /// /// <returns>The response from the ListDomains service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.InvalidNextTokenException"> /// The specified NextToken is not valid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public ListDomainsResponse ListDomains() { return ListDomains(new ListDomainsRequest()); } /// <summary> /// The <code>ListDomains</code> operation lists all domains associated with the Access /// Key ID. It returns domain names up to the limit set by <a href="#MaxNumberOfDomains">MaxNumberOfDomains</a>. /// A <a href="#NextToken">NextToken</a> is returned if there are more than <code>MaxNumberOfDomains</code> /// domains. Calling <code>ListDomains</code> successive times with the <code>NextToken</code> /// provided by the operation returns up to <code>MaxNumberOfDomains</code> more domain /// names with each successive operation call. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListDomains service method.</param> /// /// <returns>The response from the ListDomains service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.InvalidNextTokenException"> /// The specified NextToken is not valid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public ListDomainsResponse ListDomains(ListDomainsRequest request) { var marshaller = new ListDomainsRequestMarshaller(); var unmarshaller = ListDomainsResponseUnmarshaller.Instance; return Invoke<ListDomainsRequest,ListDomainsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListDomains operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDomains operation on AmazonSimpleDBClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListDomains /// operation.</returns> public IAsyncResult BeginListDomains(ListDomainsRequest request, AsyncCallback callback, object state) { var marshaller = new ListDomainsRequestMarshaller(); var unmarshaller = ListDomainsResponseUnmarshaller.Instance; return BeginInvoke<ListDomainsRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListDomains operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListDomains.</param> /// /// <returns>Returns a ListDomainsResult from SimpleDB.</returns> public ListDomainsResponse EndListDomains(IAsyncResult asyncResult) { return EndInvoke<ListDomainsResponse>(asyncResult); } #endregion #region PutAttributes /// <summary> /// The PutAttributes operation creates or replaces attributes in an item. The client /// may specify new attributes using a combination of the <code>Attribute.X.Name</code> /// and <code>Attribute.X.Value</code> parameters. The client specifies the first attribute /// by the parameters <code>Attribute.0.Name</code> and <code>Attribute.0.Value</code>, /// the second attribute by the parameters <code>Attribute.1.Name</code> and <code>Attribute.1.Value</code>, /// and so on. /// /// /// <para> /// Attributes are uniquely identified in an item by their name/value combination. For /// example, a single item can have the attributes <code>{ "first_name", "first_value" /// }</code> and <code>{ "first_name", second_value" }</code>. However, it cannot have /// two attribute instances where both the <code>Attribute.X.Name</code> and <code>Attribute.X.Value</code> /// are the same. /// </para> /// /// <para> /// Optionally, the requestor can supply the <code>Replace</code> parameter for each /// individual attribute. Setting this value to <code>true</code> causes the new attribute /// value to replace the existing attribute value(s). For example, if an item has the /// attributes <code>{ 'a', '1' }</code>, <code>{ 'b', '2'}</code> and <code>{ 'b', '3' /// }</code> and the requestor calls <code>PutAttributes</code> using the attributes <code>{ /// 'b', '4' }</code> with the <code>Replace</code> parameter set to true, the final attributes /// of the item are changed to <code>{ 'a', '1' }</code> and <code>{ 'b', '4' }</code>, /// which replaces the previous values of the 'b' attribute with the new value. /// </para> /// /// <para> /// You cannot specify an empty string as an attribute name. /// </para> /// /// <para> /// Because Amazon SimpleDB makes multiple copies of client data and uses an eventual /// consistency update model, an immediate <a>GetAttributes</a> or <a>Select</a> operation /// (read) immediately after a <a>PutAttributes</a> or <a>DeleteAttributes</a> operation /// (write) might not return the updated data. /// </para> /// /// <para> /// The following limitations are enforced for this operation: <ul> <li>256 total attribute /// name-value pairs per item</li> <li>One billion attributes per domain</li> <li>10 GB /// of total user data storage per domain</li> </ul> /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutAttributes service method.</param> /// /// <returns>The response from the PutAttributes service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.AttributeDoesNotExistException"> /// The specified attribute does not exist. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberDomainAttributesExceededException"> /// Too many attributes in this domain. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberDomainBytesExceededException"> /// Too many bytes in this domain. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NumberItemAttributesExceededException"> /// Too many attributes in this item. /// </exception> public PutAttributesResponse PutAttributes(PutAttributesRequest request) { var marshaller = new PutAttributesRequestMarshaller(); var unmarshaller = PutAttributesResponseUnmarshaller.Instance; return Invoke<PutAttributesRequest,PutAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutAttributes operation on AmazonSimpleDBClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutAttributes /// operation.</returns> public IAsyncResult BeginPutAttributes(PutAttributesRequest request, AsyncCallback callback, object state) { var marshaller = new PutAttributesRequestMarshaller(); var unmarshaller = PutAttributesResponseUnmarshaller.Instance; return BeginInvoke<PutAttributesRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutAttributes operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutAttributes.</param> /// /// <returns>Returns a PutAttributesResult from SimpleDB.</returns> public PutAttributesResponse EndPutAttributes(IAsyncResult asyncResult) { return EndInvoke<PutAttributesResponse>(asyncResult); } #endregion #region Select /// <summary> /// The <code>Select</code> operation returns a set of attributes for <code>ItemNames</code> /// that match the select expression. <code>Select</code> is similar to the standard SQL /// SELECT statement. /// /// /// <para> /// The total size of the response cannot exceed 1 MB in total size. Amazon SimpleDB /// automatically adjusts the number of items returned per page to enforce this limit. /// For example, if the client asks to retrieve 2500 items, but each individual item is /// 10 kB in size, the system returns 100 items and an appropriate <code>NextToken</code> /// so the client can access the next page of results. /// </para> /// /// <para> /// For information on how to construct select expressions, see Using Select to Create /// Amazon SimpleDB Queries in the Developer Guide. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the Select service method.</param> /// /// <returns>The response from the Select service method, as returned by SimpleDB.</returns> /// <exception cref="Amazon.SimpleDB.Model.InvalidNextTokenException"> /// The specified NextToken is not valid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidNumberPredicatesException"> /// Too many predicates exist in the query expression. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidNumberValueTestsException"> /// Too many predicates exist in the query expression. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.InvalidQueryExpressionException"> /// The specified query expression syntax is not valid. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.MissingParameterException"> /// The request must contain the specified missing parameter. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.NoSuchDomainException"> /// The specified domain does not exist. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.RequestTimeoutException"> /// A timeout occurred when attempting to query the specified domain with specified query /// expression. /// </exception> /// <exception cref="Amazon.SimpleDB.Model.TooManyRequestedAttributesException"> /// Too many attributes requested. /// </exception> public SelectResponse Select(SelectRequest request) { var marshaller = new SelectRequestMarshaller(); var unmarshaller = SelectResponseUnmarshaller.Instance; return Invoke<SelectRequest,SelectResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the Select operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Select operation on AmazonSimpleDBClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSelect /// operation.</returns> public IAsyncResult BeginSelect(SelectRequest request, AsyncCallback callback, object state) { var marshaller = new SelectRequestMarshaller(); var unmarshaller = SelectResponseUnmarshaller.Instance; return BeginInvoke<SelectRequest>(request, marshaller, unmarshaller, callback, state); } /// <summary> /// Finishes the asynchronous execution of the Select operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginSelect.</param> /// /// <returns>Returns a SelectResult from SimpleDB.</returns> public SelectResponse EndSelect(IAsyncResult asyncResult) { return EndInvoke<SelectResponse>(asyncResult); } #endregion } }
using NUnit.Framework; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework.Tests { [TestFixture] public class RenderMaterialsTests { [SetUp] public void Init() { } [Test] public void RenderMaterial_OSDFromToTest() { RenderMaterial mat = new RenderMaterial(UUID.Zero, UUID.Zero); OSD map = mat.GetOSD(); RenderMaterial matFromOSD = RenderMaterial.FromOSD(map); Assert.That(mat, Is.EqualTo(matFromOSD)); Assert.That(matFromOSD.NormalID, Is.EqualTo(UUID.Zero)); Assert.That(matFromOSD.NormalOffsetX, Is.EqualTo(0.0f)); Assert.That(matFromOSD.NormalOffsetY, Is.EqualTo(0.0f)); Assert.That(matFromOSD.NormalRepeatX, Is.EqualTo(1.0f)); Assert.That(matFromOSD.NormalRepeatY, Is.EqualTo(1.0f)); Assert.That(matFromOSD.NormalRotation, Is.EqualTo(0.0f)); Assert.That(matFromOSD.SpecularID, Is.EqualTo(UUID.Zero)); Assert.That(matFromOSD.SpecularOffsetX, Is.EqualTo(0.0f)); Assert.That(matFromOSD.SpecularOffsetY, Is.EqualTo(0.0f)); Assert.That(matFromOSD.SpecularRepeatX, Is.EqualTo(1.0f)); Assert.That(matFromOSD.SpecularRepeatY, Is.EqualTo(1.0f)); Assert.That(matFromOSD.SpecularRotation, Is.EqualTo(0.0f)); Assert.That(matFromOSD.SpecularLightColorR, Is.EqualTo(255)); Assert.That(matFromOSD.SpecularLightColorG, Is.EqualTo(255)); Assert.That(matFromOSD.SpecularLightColorB, Is.EqualTo(255)); Assert.That(matFromOSD.SpecularLightColorA, Is.EqualTo(255)); Assert.That(matFromOSD.SpecularLightExponent, Is.EqualTo(RenderMaterial.DEFAULT_SPECULAR_LIGHT_EXPONENT)); Assert.That(matFromOSD.EnvironmentIntensity, Is.EqualTo(RenderMaterial.DEFAULT_ENV_INTENSITY)); Assert.That(matFromOSD.DiffuseAlphaMode, Is.EqualTo((byte)RenderMaterial.eDiffuseAlphaMode.DIFFUSE_ALPHA_MODE_BLEND)); Assert.That(matFromOSD.AlphaMaskCutoff, Is.EqualTo(0)); } [Test] public void RenderMaterial_ToFromOSDPreservesValues() { RenderMaterial mat = new RenderMaterial(); mat.NormalID = UUID.Random(); mat.NormalOffsetX = 2.0f; mat.NormalOffsetY = 2.0f; mat.NormalRepeatX = 2.0f; mat.NormalRepeatY = 2.0f; mat.NormalRotation = 180.0f; mat.SpecularID = UUID.Random(); mat.SpecularOffsetX = 2.0f; mat.SpecularOffsetY = 2.0f; mat.SpecularRepeatX = 2.0f; mat.SpecularRepeatY = 2.0f; mat.SpecularRotation = 180.0f; mat.SpecularLightColorR = 127; mat.SpecularLightColorG = 127; mat.SpecularLightColorB = 127; mat.SpecularLightColorA = 255; mat.SpecularLightExponent = 2; mat.EnvironmentIntensity = 2; mat.DiffuseAlphaMode = (byte)RenderMaterial.eDiffuseAlphaMode.DIFFUSE_ALPHA_MODE_MASK; mat.AlphaMaskCutoff = 2; OSD map = mat.GetOSD(); RenderMaterial newmat = RenderMaterial.FromOSD(map); Assert.That(newmat, Is.EqualTo(mat)); } [Test] public void RenderMaterial_SerializationPreservesValues() { RenderMaterial mat = new RenderMaterial(); mat.NormalID = UUID.Random(); mat.NormalOffsetX = 2.0f; mat.NormalOffsetY = 2.0f; mat.NormalRepeatX = 2.0f; mat.NormalRepeatY = 2.0f; mat.NormalRotation = 180.0f; mat.SpecularID = UUID.Random(); mat.SpecularOffsetX = 2.0f; mat.SpecularOffsetY = 2.0f; mat.SpecularRepeatX = 2.0f; mat.SpecularRepeatY = 2.0f; mat.SpecularRotation = 180.0f; mat.SpecularLightColorR = 127; mat.SpecularLightColorG = 127; mat.SpecularLightColorB = 127; mat.SpecularLightColorA = 255; mat.SpecularLightExponent = 2; mat.EnvironmentIntensity = 2; mat.DiffuseAlphaMode = (byte)RenderMaterial.eDiffuseAlphaMode.DIFFUSE_ALPHA_MODE_MASK; mat.AlphaMaskCutoff = 2; byte[] bytes = mat.ToBytes(); RenderMaterial newmat = RenderMaterial.FromBytes(bytes, 0, bytes.Length); Assert.That(newmat, Is.EqualTo(mat)); } [Test] public void RenderMaterial_ToFromBinaryTest() { RenderMaterial mat = new RenderMaterial(); RenderMaterials mats = new RenderMaterials(); UUID key = mats.AddMaterial(mat); byte[] bytes = mats.ToBytes(); RenderMaterials newmats = RenderMaterials.FromBytes(bytes, 0); Assert.DoesNotThrow(() => { RenderMaterial newmat = newmats.GetMaterial(key); Assert.That(mat, Is.EqualTo(newmat)); }); } [Test] public void RenderMaterial_ColorValueToFromMaterialTest() { RenderMaterial mat = new RenderMaterial(); mat.SpecularLightColorR = 127; mat.SpecularLightColorG = 127; mat.SpecularLightColorB = 127; mat.SpecularLightColorA = 255; byte[] bytes = mat.ToBytes(); RenderMaterial newmat = RenderMaterial.FromBytes(bytes, 0, bytes.Length); Assert.That(mat, Is.EqualTo(newmat)); Assert.That(mat.SpecularLightColorR, Is.EqualTo(127)); Assert.That(mat.SpecularLightColorG, Is.EqualTo(127)); Assert.That(mat.SpecularLightColorB, Is.EqualTo(127)); Assert.That(mat.SpecularLightColorA, Is.EqualTo(255)); } [Test] public void RenderMaterial_CopiedMaterialGeneratesTheSameMaterialID() { RenderMaterial mat = new RenderMaterial(); RenderMaterial matCopy = (RenderMaterial)mat.Clone(); UUID matID = RenderMaterial.GenerateMaterialID(mat); UUID matCopyID = RenderMaterial.GenerateMaterialID(matCopy); Assert.That(mat, Is.EqualTo(matCopy)); Assert.That(matID, Is.EqualTo(matCopyID)); } [Test] public void RenderMaterial_DefaultConstructedMaterialsGeneratesTheSameMaterialID() { RenderMaterial mat = new RenderMaterial(); RenderMaterial mat2 = new RenderMaterial(); UUID matID = RenderMaterial.GenerateMaterialID(mat); UUID mat2ID = RenderMaterial.GenerateMaterialID(mat2); Assert.That(mat, Is.EqualTo(mat2)); Assert.That(matID, Is.EqualTo(mat2ID)); } [Test] public void RenderMaterial_SerializedMaterialGeneratesTheSameMaterialID() { RenderMaterial mat = new RenderMaterial(); UUID matID = new UUID(mat.ComputeMD5Hash(), 0); byte[] matData = mat.ToBytes(); RenderMaterial newmat = RenderMaterial.FromBytes(matData, 0, matData.Length); UUID newmatID = RenderMaterial.GenerateMaterialID(newmat); Assert.That(mat, Is.EqualTo(newmat)); Assert.That(matID, Is.EqualTo(newmatID)); } [Test] public void RenderMaterial_SerializedMaterialsDataGeneratesTheSameMaterialID() { RenderMaterials materials = new RenderMaterials(); RenderMaterial mat = new RenderMaterial(); UUID matID = materials.AddMaterial(mat); byte[] matData = materials.ToBytes(); RenderMaterials newMaterials = RenderMaterials.FromBytes(matData, 0, matData.Length); Assert.That(materials, Is.EqualTo(newMaterials)); Assert.DoesNotThrow(() => { RenderMaterial newmat = newMaterials.GetMaterial(matID); UUID newmatID = RenderMaterial.GenerateMaterialID(newmat); Assert.That(mat, Is.EqualTo(newmat)); Assert.That(matID, Is.EqualTo(newmatID)); }); } [Test] public void RenderMaterial_DifferentMaterialsGeneratesDifferentMaterialID() { RenderMaterial mat = new RenderMaterial(); RenderMaterial mat2 = new RenderMaterial(); mat2.NormalID = UUID.Random(); Assert.AreNotEqual(mat, mat2); UUID matID = RenderMaterial.GenerateMaterialID(mat); UUID mat2ID = RenderMaterial.GenerateMaterialID(mat2); Assert.AreNotEqual(matID, mat2ID); } [Test] public void RenderMaterials_CopiedMaterialsGeneratesTheSameMaterialID() { RenderMaterial mat = new RenderMaterial(); RenderMaterials mats = new RenderMaterials(); UUID matID = mats.AddMaterial(mat); RenderMaterials matsCopy = mats.Copy(); Assert.True(mats.ContainsMaterial(matID)); Assert.True(matsCopy.ContainsMaterial(matID)); } } }
// 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; /// <summary> /// System.IConvertible.ToSByte(System.IFormatProvider) /// </summary> public class DoubleIConvertibleToSByte { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); // retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Convert a random Double( <= 0.5 ) to sbyte"); try { Double i1; do i1 = (Double)TestLibrary.Generator.GetDouble(-55); while (i1 > 0.5D); IConvertible Icon1 = (IConvertible)i1; if (Icon1.ToSByte(null) != 0) { TestLibrary.TestFramework.LogError("001.1", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Convert a random Double( > 0.5 ) to sbyte"); try { Double i1; do i1 = (Double)TestLibrary.Generator.GetDouble(-55); while (i1 <= 0.5D); IConvertible Icon1 = (IConvertible)i1; if (Icon1.ToSByte(null) != 1) { TestLibrary.TestFramework.LogError("002.1", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.1", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert zero to sbyte "); try { Double i1 = 0; IConvertible Icon1 = (IConvertible)i1; if (Icon1.ToSByte(null) != 0) { TestLibrary.TestFramework.LogError("003.1", "The result is not zero as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert (double)SByte.MaxValue to sbyte."); try { Double i1 = (Double)SByte.MaxValue; IConvertible Icon1 = (IConvertible)i1; if (Icon1.ToSByte(null) != SByte.MaxValue) { TestLibrary.TestFramework.LogError("004.1", "The result is not expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Convert (double)SByte.MinValue to sbyte."); try { Double i1 = (Double)SByte.MinValue; IConvertible Icon1 = (IConvertible)i1; if (Icon1.ToSByte(null) != SByte.MinValue) { TestLibrary.TestFramework.LogError("005.1", "The result is not expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases //public bool NegTest1() //{ // bool retVal = true; // TestLibrary.TestFramework.BeginScenario("NegTest1: "); // try // { // // // // Add your test logic here // // // } // catch (Exception e) // { // TestLibrary.TestFramework.LogError("101", "Unexpected exception: " + e); // TestLibrary.TestFramework.LogInformation(e.StackTrace); // retVal = false; // } // return retVal; //} #endregion #endregion public static int Main() { DoubleIConvertibleToSByte test = new DoubleIConvertibleToSByte(); TestLibrary.TestFramework.BeginTestCase("DoubleIConvertibleToSByte"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { internal abstract class GreaterThanInstruction : Instruction { private readonly object _nullValue; private static Instruction s_SByte, s_Int16, s_Char, s_Int32, s_Int64, s_Byte, s_UInt16, s_UInt32, s_UInt64, s_Single, s_Double; private static Instruction s_liftedToNullSByte, s_liftedToNullInt16, s_liftedToNullChar, s_liftedToNullInt32, s_liftedToNullInt64, s_liftedToNullByte, s_liftedToNullUInt16, s_liftedToNullUInt32, s_liftedToNullUInt64, s_liftedToNullSingle, s_liftedToNullDouble; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "GreaterThan"; private GreaterThanInstruction(object nullValue) { _nullValue = nullValue; } private sealed class GreaterThanSByte : GreaterThanInstruction { public GreaterThanSByte(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((sbyte)left > (sbyte)right); } return 1; } } private sealed class GreaterThanInt16 : GreaterThanInstruction { public GreaterThanInt16(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((short)left > (short)right); } return 1; } } private sealed class GreaterThanChar : GreaterThanInstruction { public GreaterThanChar(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((char)left > (char)right); } return 1; } } private sealed class GreaterThanInt32 : GreaterThanInstruction { public GreaterThanInt32(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((int)left > (int)right); } return 1; } } private sealed class GreaterThanInt64 : GreaterThanInstruction { public GreaterThanInt64(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((long)left > (long)right); } return 1; } } private sealed class GreaterThanByte : GreaterThanInstruction { public GreaterThanByte(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((byte)left > (byte)right); } return 1; } } private sealed class GreaterThanUInt16 : GreaterThanInstruction { public GreaterThanUInt16(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((ushort)left > (ushort)right); } return 1; } } private sealed class GreaterThanUInt32 : GreaterThanInstruction { public GreaterThanUInt32(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((uint)left > (uint)right); } return 1; } } private sealed class GreaterThanUInt64 : GreaterThanInstruction { public GreaterThanUInt64(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((ulong)left > (ulong)right); } return 1; } } private sealed class GreaterThanSingle : GreaterThanInstruction { public GreaterThanSingle(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((float)left > (float)right); } return 1; } } private sealed class GreaterThanDouble : GreaterThanInstruction { public GreaterThanDouble(object nullValue) : base(nullValue) { } public override int Run(InterpretedFrame frame) { object right = frame.Pop(); object left = frame.Pop(); if (left == null || right == null) { frame.Push(_nullValue); } else { frame.Push((double)left > (double)right); } return 1; } } public static Instruction Create(Type type, bool liftedToNull = false) { Debug.Assert(!type.IsEnum); if (liftedToNull) { switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.SByte: return s_liftedToNullSByte ?? (s_liftedToNullSByte = new GreaterThanSByte(null)); case TypeCode.Int16: return s_liftedToNullInt16 ?? (s_liftedToNullInt16 = new GreaterThanInt16(null)); case TypeCode.Char: return s_liftedToNullChar ?? (s_liftedToNullChar = new GreaterThanChar(null)); case TypeCode.Int32: return s_liftedToNullInt32 ?? (s_liftedToNullInt32 = new GreaterThanInt32(null)); case TypeCode.Int64: return s_liftedToNullInt64 ?? (s_liftedToNullInt64 = new GreaterThanInt64(null)); case TypeCode.Byte: return s_liftedToNullByte ?? (s_liftedToNullByte = new GreaterThanByte(null)); case TypeCode.UInt16: return s_liftedToNullUInt16 ?? (s_liftedToNullUInt16 = new GreaterThanUInt16(null)); case TypeCode.UInt32: return s_liftedToNullUInt32 ?? (s_liftedToNullUInt32 = new GreaterThanUInt32(null)); case TypeCode.UInt64: return s_liftedToNullUInt64 ?? (s_liftedToNullUInt64 = new GreaterThanUInt64(null)); case TypeCode.Single: return s_liftedToNullSingle ?? (s_liftedToNullSingle = new GreaterThanSingle(null)); case TypeCode.Double: return s_liftedToNullDouble ?? (s_liftedToNullDouble = new GreaterThanDouble(null)); default: throw ContractUtils.Unreachable; } } else { switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.SByte: return s_SByte ?? (s_SByte = new GreaterThanSByte(Utils.BoxedFalse)); case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new GreaterThanInt16(Utils.BoxedFalse)); case TypeCode.Char: return s_Char ?? (s_Char = new GreaterThanChar(Utils.BoxedFalse)); case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new GreaterThanInt32(Utils.BoxedFalse)); case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new GreaterThanInt64(Utils.BoxedFalse)); case TypeCode.Byte: return s_Byte ?? (s_Byte = new GreaterThanByte(Utils.BoxedFalse)); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new GreaterThanUInt16(Utils.BoxedFalse)); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new GreaterThanUInt32(Utils.BoxedFalse)); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new GreaterThanUInt64(Utils.BoxedFalse)); case TypeCode.Single: return s_Single ?? (s_Single = new GreaterThanSingle(Utils.BoxedFalse)); case TypeCode.Double: return s_Double ?? (s_Double = new GreaterThanDouble(Utils.BoxedFalse)); default: throw ContractUtils.Unreachable; } } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSSF.Util { using System; using System.Collections; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; /// <summary> /// Various utility functions that make working with a cells and rows easier. The various /// methods that deal with style's allow you to Create your HSSFCellStyles as you need them. /// When you apply a style change to a cell, the code will attempt to see if a style already /// exists that meets your needs. If not, then it will Create a new style. This is to prevent /// creating too many styles. there is an upper limit in Excel on the number of styles that /// can be supported. /// @author Eric Pugh epugh@upstate.com /// </summary> internal class HSSFCellUtil { public static String ALIGNMENT = "alignment"; public static String BORDER_BOTTOM = "borderBottom"; public static String BORDER_LEFT = "borderLeft"; public static String BORDER_RIGHT = "borderRight"; public static String BORDER_TOP = "borderTop"; public static String BOTTOM_BORDER_COLOR = "bottomBorderColor"; public static String DATA_FORMAT = "dataFormat"; public static String FILL_BACKGROUND_COLOR = "fillBackgroundColor"; public static String FILL_FOREGROUND_COLOR = "fillForegroundColor"; public static String FILL_PATTERN = "fillPattern"; public static String FONT = "font"; public static String HIDDEN = "hidden"; public static String INDENTION = "indention"; public static String LEFT_BORDER_COLOR = "leftBorderColor"; public static String LOCKED = "locked"; public static String RIGHT_BORDER_COLOR = "rightBorderColor"; public static String ROTATION = "rotation"; public static String TOP_BORDER_COLOR = "topBorderColor"; public static String VERTICAL_ALIGNMENT = "verticalAlignment"; public static String WRAP_TEXT = "wrapText"; private static UnicodeMapping[] unicodeMappings; static HSSFCellUtil() { unicodeMappings = new UnicodeMapping[15]; unicodeMappings[0] = um("alpha", "\u03B1"); unicodeMappings[1] = um("beta", "\u03B2"); unicodeMappings[2] = um("gamma", "\u03B3"); unicodeMappings[3] = um("delta", "\u03B4"); unicodeMappings[4] = um("epsilon", "\u03B5"); unicodeMappings[5] = um("zeta", "\u03B6"); unicodeMappings[6] = um("eta", "\u03B7"); unicodeMappings[7] = um("theta", "\u03B8"); unicodeMappings[8] = um("iota", "\u03B9"); unicodeMappings[9] = um("kappa", "\u03BA"); unicodeMappings[10] = um("lambda", "\u03BB"); unicodeMappings[11] = um("mu", "\u03BC"); unicodeMappings[12] = um("nu", "\u03BD"); unicodeMappings[13] = um("xi", "\u03BE"); unicodeMappings[14] = um("omicron", "\u03BF"); } private class UnicodeMapping { public String entityName; public String resolvedValue; public UnicodeMapping(String pEntityName, String pResolvedValue) { entityName = "&" + pEntityName + ";"; resolvedValue = pResolvedValue; } } private HSSFCellUtil() { // no instances of this class } /// <summary> /// Get a row from the spreadsheet, and Create it if it doesn't exist. /// </summary> /// <param name="rowCounter">The 0 based row number</param> /// <param name="sheet">The sheet that the row is part of.</param> /// <returns>The row indicated by the rowCounter</returns> public static NPOI.SS.UserModel.IRow GetRow(int rowCounter, HSSFSheet sheet) { NPOI.SS.UserModel.IRow row = sheet.GetRow(rowCounter); if (row == null) { row = sheet.CreateRow(rowCounter); } return row; } /// <summary> /// Get a specific cell from a row. If the cell doesn't exist, /// </summary> /// <param name="row">The row that the cell is part of</param> /// <param name="column">The column index that the cell is in.</param> /// <returns>The cell indicated by the column.</returns> public static NPOI.SS.UserModel.ICell GetCell(NPOI.SS.UserModel.IRow row, int column) { NPOI.SS.UserModel.ICell cell = row.GetCell(column); if (cell == null) { cell = row.CreateCell(column); } return cell; } /// <summary> /// Creates a cell, gives it a value, and applies a style if provided /// </summary> /// <param name="row">the row to Create the cell in</param> /// <param name="column">the column index to Create the cell in</param> /// <param name="value">The value of the cell</param> /// <param name="style">If the style is not null, then Set</param> /// <returns>A new HSSFCell</returns> public static NPOI.SS.UserModel.ICell CreateCell(NPOI.SS.UserModel.IRow row, int column, String value, HSSFCellStyle style) { NPOI.SS.UserModel.ICell cell = GetCell(row, column); cell.SetCellValue(new HSSFRichTextString(value)); if (style != null) { cell.CellStyle = (style); } return cell; } /// <summary> /// Create a cell, and give it a value. /// </summary> /// <param name="row">the row to Create the cell in</param> /// <param name="column">the column index to Create the cell in</param> /// <param name="value">The value of the cell</param> /// <returns>A new HSSFCell.</returns> public static NPOI.SS.UserModel.ICell CreateCell(NPOI.SS.UserModel.IRow row, int column, String value) { return CreateCell(row, column, value, null); } /// <summary> /// Take a cell, and align it. /// </summary> /// <param name="cell">the cell to Set the alignment for</param> /// <param name="workbook">The workbook that is being worked with.</param> /// <param name="align">the column alignment to use.</param> public static void SetAlignment(ICell cell, HSSFWorkbook workbook, short align) { SetCellStyleProperty(cell, workbook, ALIGNMENT, align); } /// <summary> /// Take a cell, and apply a font to it /// </summary> /// <param name="cell">the cell to Set the alignment for</param> /// <param name="workbook">The workbook that is being worked with.</param> /// <param name="font">The HSSFFont that you want to Set...</param> public static void SetFont(ICell cell, HSSFWorkbook workbook, HSSFFont font) { SetCellStyleProperty(cell, workbook, FONT, font); } /** * This method attempt to find an already existing HSSFCellStyle that matches * what you want the style to be. If it does not find the style, then it * Creates a new one. If it does Create a new one, then it applies the * propertyName and propertyValue to the style. This is necessary because * Excel has an upper limit on the number of Styles that it supports. * *@param workbook The workbook that is being worked with. *@param propertyName The name of the property that is to be * changed. *@param propertyValue The value of the property that is to be * changed. *@param cell The cell that needs it's style changes *@exception NestableException Thrown if an error happens. */ public static void SetCellStyleProperty(NPOI.SS.UserModel.ICell cell, HSSFWorkbook workbook, String propertyName, Object propertyValue) { NPOI.SS.UserModel.ICellStyle originalStyle = cell.CellStyle; NPOI.SS.UserModel.ICellStyle newStyle = null; Hashtable values = GetFormatProperties(originalStyle); values[propertyName] = propertyValue; // index seems like what index the cellstyle is in the list of styles for a workbook. // not good to compare on! short numberCellStyles = workbook.NumCellStyles; for (short i = 0; i < numberCellStyles; i++) { NPOI.SS.UserModel.ICellStyle wbStyle = workbook.GetCellStyleAt(i); Hashtable wbStyleMap = GetFormatProperties(wbStyle); if (wbStyleMap.Equals(values)) { newStyle = wbStyle; break; } } if (newStyle == null) { newStyle = workbook.CreateCellStyle(); SetFormatProperties(newStyle, workbook, values); } cell.CellStyle = (newStyle); } /// <summary> /// Returns a map containing the format properties of the given cell style. /// </summary> /// <param name="style">cell style</param> /// <returns>map of format properties (String -&gt; Object)</returns> private static Hashtable GetFormatProperties(NPOI.SS.UserModel.ICellStyle style) { Hashtable properties = new Hashtable(); PutShort(properties, ALIGNMENT, (short)style.Alignment); PutShort(properties, BORDER_BOTTOM, (short)style.BorderBottom); PutShort(properties, BORDER_LEFT, (short)style.BorderLeft); PutShort(properties, BORDER_RIGHT, (short)style.BorderRight); PutShort(properties, BORDER_TOP, (short)style.BorderTop); PutShort(properties, BOTTOM_BORDER_COLOR, style.BottomBorderColor); PutShort(properties, DATA_FORMAT, style.DataFormat); PutShort(properties, FILL_BACKGROUND_COLOR, style.FillBackgroundColor); PutShort(properties, FILL_FOREGROUND_COLOR, style.FillForegroundColor); PutShort(properties, FILL_PATTERN, (short)style.FillPattern); PutShort(properties, FONT, style.FontIndex); PutBoolean(properties, HIDDEN, style.IsHidden); PutShort(properties, INDENTION, style.Indention); PutShort(properties, LEFT_BORDER_COLOR, style.LeftBorderColor); PutBoolean(properties, LOCKED, style.IsLocked); PutShort(properties, RIGHT_BORDER_COLOR, style.RightBorderColor); PutShort(properties, ROTATION, style.Rotation); PutShort(properties, TOP_BORDER_COLOR, style.TopBorderColor); PutShort(properties, VERTICAL_ALIGNMENT, (short)style.VerticalAlignment); PutBoolean(properties, WRAP_TEXT, style.WrapText); return properties; } /// <summary> /// Sets the format properties of the given style based on the given map. /// </summary> /// <param name="style">The cell style</param> /// <param name="workbook">The parent workbook.</param> /// <param name="properties">The map of format properties (String -&gt; Object).</param> private static void SetFormatProperties( NPOI.SS.UserModel.ICellStyle style, HSSFWorkbook workbook, Hashtable properties) { style.Alignment = (NPOI.SS.UserModel.HorizontalAlignment)GetShort(properties, ALIGNMENT); style.BorderBottom = (NPOI.SS.UserModel.BorderStyle)GetShort(properties, BORDER_BOTTOM); style.BorderLeft = (NPOI.SS.UserModel.BorderStyle)GetShort(properties, BORDER_LEFT); style.BorderRight = (NPOI.SS.UserModel.BorderStyle)GetShort(properties, BORDER_RIGHT); style.BorderTop = (NPOI.SS.UserModel.BorderStyle)GetShort(properties, BORDER_TOP); style.BottomBorderColor = (GetShort(properties, BOTTOM_BORDER_COLOR)); style.DataFormat = (GetShort(properties, DATA_FORMAT)); style.FillBackgroundColor = (GetShort(properties, FILL_BACKGROUND_COLOR)); style.FillForegroundColor = (GetShort(properties, FILL_FOREGROUND_COLOR)); style.FillPattern = (NPOI.SS.UserModel.FillPatternType)GetShort(properties, FILL_PATTERN); style.SetFont(workbook.GetFontAt(GetShort(properties, FONT))); style.IsHidden = (GetBoolean(properties, HIDDEN)); style.Indention = (GetShort(properties, INDENTION)); style.LeftBorderColor = (GetShort(properties, LEFT_BORDER_COLOR)); style.IsLocked = (GetBoolean(properties, LOCKED)); style.RightBorderColor = (GetShort(properties, RIGHT_BORDER_COLOR)); style.Rotation = (GetShort(properties, ROTATION)); style.TopBorderColor = (GetShort(properties, TOP_BORDER_COLOR)); style.VerticalAlignment = (NPOI.SS.UserModel.VerticalAlignment)GetShort(properties, VERTICAL_ALIGNMENT); style.WrapText = (GetBoolean(properties, WRAP_TEXT)); } /// <summary> /// Utility method that returns the named short value form the given map. /// Returns zero if the property does not exist, or is not a {@link Short}. /// </summary> /// <param name="properties">The map of named properties (String -&gt; Object)</param> /// <param name="name">The property name.</param> /// <returns>property value, or zero</returns> private static short GetShort(Hashtable properties, String name) { Object value = properties[name]; if (value is short) { return (short)value; } else { return 0; } } /// <summary> /// Utility method that returns the named boolean value form the given map. /// Returns false if the property does not exist, or is not a {@link Boolean}. /// </summary> /// <param name="properties">map of properties (String -&gt; Object)</param> /// <param name="name">The property name.</param> /// <returns>property value, or false</returns> private static bool GetBoolean(Hashtable properties, String name) { Object value = properties[name]; if (value is Boolean) { return ((Boolean)value); } else { return false; } } /// <summary> /// Utility method that Puts the named short value to the given map. /// </summary> /// <param name="properties">The map of properties (String -&gt; Object).</param> /// <param name="name">The property name.</param> /// <param name="value">The property value.</param> private static void PutShort(Hashtable properties, String name, short value) { properties[name] = value; } /// <summary> /// Utility method that Puts the named boolean value to the given map. /// </summary> /// <param name="properties">map of properties (String -&gt; Object)</param> /// <param name="name">property name</param> /// <param name="value">property value</param> private static void PutBoolean(Hashtable properties, String name, bool value) { properties[name] = value; } /// <summary> /// Looks for text in the cell that should be unicode, like alpha; and provides the /// unicode version of it. /// </summary> /// <param name="cell">The cell to check for unicode values</param> /// <returns>transalted to unicode</returns> public static ICell TranslateUnicodeValues(ICell cell) { String s = cell.RichStringCellValue.String; bool foundUnicode = false; String lowerCaseStr = s.ToLower(); for (int i = 0; i < unicodeMappings.Length; i++) { UnicodeMapping entry = unicodeMappings[i]; String key = entry.entityName; if (lowerCaseStr.IndexOf(key, StringComparison.Ordinal) != -1) { s = s.Replace(key, entry.resolvedValue); foundUnicode = true; } } if (foundUnicode) { cell.SetCellValue(new HSSFRichTextString(s)); } return cell; } private static UnicodeMapping um(String entityName, String resolvedValue) { return new UnicodeMapping(entityName, resolvedValue); } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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. ************************************************************************************/ //#define OVR_USE_PROJ_MATRIX using System; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// A head-tracked stereoscopic virtual reality camera rig. /// </summary> //[ExecuteInEditMode] SHJO MODIFIED public class OVRCameraRig : MonoBehaviour { /// <summary> /// The left eye camera. /// </summary> private Camera leftEyeCamera; /// <summary> /// The right eye camera. /// </summary> private Camera rightEyeCamera; /// <summary> /// Always coincides with the pose of the left eye. /// </summary> public Transform leftEyeAnchor { get; private set; } /// <summary> /// Always coincides with average of the left and right eye poses. /// </summary> public Transform centerEyeAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the right eye. /// </summary> public Transform rightEyeAnchor { get; private set; } private bool needsCameraConfigure; public bool StopUpdateAnchors = false; #region Unity Messages private void Awake() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; needsCameraConfigure = true; } private void Start() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateCameras(); UpdateAnchors(); } #if !UNITY_ANDROID || UNITY_EDITOR private void LateUpdate() #else private void Update() #endif { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateCameras(); UpdateAnchors(); } #endregion private void UpdateAnchors() { OVRPose leftEye = OVRManager.display.GetEyePose(OVREye.Left); OVRPose rightEye = OVRManager.display.GetEyePose(OVREye.Right); //Manager.Instance.CameraRotation = leftEye.orientation.eulerAngles; EarthManager.Instance.CameraRotation = leftEye.orientation.eulerAngles; EarthManager.Instance.CameraOrientation = leftEye.orientation; //Debug.Log (leftEye.orientation.eulerAngles); //Debug.Log (Manager.Instance.CameraOrientation); if (StopUpdateAnchors != true) { leftEyeAnchor.localRotation = leftEye.orientation; centerEyeAnchor.localRotation = leftEye.orientation; // using left eye for now rightEyeAnchor.localRotation = rightEye.orientation; leftEyeAnchor.localPosition = leftEye.position; centerEyeAnchor.localPosition = 0.5f * (leftEye.position + rightEye.position); rightEyeAnchor.localPosition = rightEye.position; } } private void UpdateCameras() { if (needsCameraConfigure) { leftEyeCamera = ConfigureCamera(OVREye.Left); rightEyeCamera = ConfigureCamera(OVREye.Right); #if !UNITY_ANDROID || UNITY_EDITOR #if OVR_USE_PROJ_MATRIX OVRManager.display.ForceSymmetricProj(false); #else OVRManager.display.ForceSymmetricProj(true); #endif needsCameraConfigure = false; #endif } } private void EnsureGameObjectIntegrity() { if (leftEyeAnchor == null) leftEyeAnchor = ConfigureEyeAnchor(OVREye.Left); if (centerEyeAnchor == null) centerEyeAnchor = ConfigureEyeAnchor(OVREye.Center); if (rightEyeAnchor == null) rightEyeAnchor = ConfigureEyeAnchor(OVREye.Right); if (leftEyeCamera == null) { leftEyeCamera = leftEyeAnchor.GetComponent<Camera>(); if (leftEyeCamera == null) { leftEyeCamera = leftEyeAnchor.gameObject.AddComponent<Camera>(); } } if (rightEyeCamera == null) { rightEyeCamera = rightEyeAnchor.GetComponent<Camera>(); if (rightEyeCamera == null) { rightEyeCamera = rightEyeAnchor.gameObject.AddComponent<Camera>(); } } } private Transform ConfigureEyeAnchor(OVREye eye) { string name = eye.ToString() + "EyeAnchor"; Transform anchor = transform.Find(name); if (anchor == null) { string oldName = "Camera" + eye.ToString(); anchor = transform.Find(oldName); } if (anchor == null) anchor = new GameObject(name).transform; anchor.parent = transform; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } private Camera ConfigureCamera(OVREye eye) { Transform anchor = (eye == OVREye.Left) ? leftEyeAnchor : rightEyeAnchor; Camera cam = anchor.GetComponent<Camera>(); OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(eye); cam.fieldOfView = eyeDesc.fov.y; cam.aspect = eyeDesc.resolution.x / eyeDesc.resolution.y; cam.rect = new Rect(0f, 0f, OVRManager.instance.virtualTextureScale, OVRManager.instance.virtualTextureScale); cam.targetTexture = OVRManager.display.GetEyeTexture(eye); // AA is documented to have no effect in deferred, but it causes black screens. if (cam.actualRenderingPath == RenderingPath.DeferredLighting) QualitySettings.antiAliasing = 0; #if !UNITY_ANDROID || UNITY_EDITOR #if OVR_USE_PROJ_MATRIX cam.projectionMatrix = OVRManager.display.GetProjection((int)eye, cam.nearClipPlane, cam.farClipPlane); #endif #endif return cam; } }
// suppress "Missing XML comment for publicly visible type or member" #pragma warning disable 1591 #region ReSharper warnings // ReSharper disable PartialTypeWithSinglePart // ReSharper disable RedundantNameQualifier // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable UnusedParameter.Local // ReSharper disable RedundantUsingDirective #endregion namespace tests { using System.Collections.Generic; [System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")] public abstract class FooServiceBase : IFoo, global::Bond.Comm.IService { public global::System.Collections.Generic.IEnumerable<global::Bond.Comm.ServiceMethodInfo> Methods { get { yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo11", Callback = foo11Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.Event}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo12", Callback = foo12Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.Event}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo12_impl", Callback = foo12_implAsync_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.Event}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo13", Callback = foo13Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.Event}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo14", Callback = foo14Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.Event}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo15", Callback = foo15Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.Event}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo21", Callback = foo21Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo22", Callback = foo22Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo23", Callback = foo23Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo24", Callback = foo24Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo31", Callback = foo31Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo32", Callback = foo32Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo33", Callback = foo33Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo._rd_foo33", Callback = _rd_foo33Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo34", Callback = foo34Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo41", Callback = foo41Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo42", Callback = foo42Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo43", Callback = foo43Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.foo44", Callback = foo44Async_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; yield return new global::Bond.Comm.ServiceMethodInfo {MethodName="tests.Foo.cq", Callback = cqAsync_Glue, CallbackType = global::Bond.Comm.ServiceCallbackType.RequestResponse}; } } public abstract void foo11Async(global::Bond.Comm.IMessage<global::Bond.Void> param); public abstract void foo12Async(global::Bond.Comm.IMessage<global::Bond.Void> param); public abstract void foo12_implAsync(global::Bond.Comm.IMessage<global::Bond.Void> param); public abstract void foo13Async(global::Bond.Comm.IMessage<BasicTypes> param); public abstract void foo14Async(global::Bond.Comm.IMessage<dummy> param); public abstract void foo15Async(global::Bond.Comm.IMessage<global::tests2.OtherBasicTypes> param); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo21Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo22Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo23Async(global::Bond.Comm.IMessage<BasicTypes> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<global::Bond.Void>> foo24Async(global::Bond.Comm.IMessage<dummy> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo31Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo32Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo33Async(global::Bond.Comm.IMessage<BasicTypes> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> _rd_foo33Async(global::Bond.Comm.IMessage<BasicTypes> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> foo34Async(global::Bond.Comm.IMessage<dummy> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo41Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo42Async(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo43Async(global::Bond.Comm.IMessage<BasicTypes> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<dummy>> foo44Async(global::Bond.Comm.IMessage<dummy> param, global::System.Threading.CancellationToken ct); public abstract global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage<BasicTypes>> cqAsync(global::Bond.Comm.IMessage<global::Bond.Void> param, global::System.Threading.CancellationToken ct); private global::System.Threading.Tasks.Task foo11Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { foo11Async(param.Convert<global::Bond.Void>()); return global::Bond.Comm.CodegenHelpers.CompletedTask; } private global::System.Threading.Tasks.Task foo12Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { foo12Async(param.Convert<global::Bond.Void>()); return global::Bond.Comm.CodegenHelpers.CompletedTask; } private global::System.Threading.Tasks.Task foo12_implAsync_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { foo12_implAsync(param.Convert<global::Bond.Void>()); return global::Bond.Comm.CodegenHelpers.CompletedTask; } private global::System.Threading.Tasks.Task foo13Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { foo13Async(param.Convert<BasicTypes>()); return global::Bond.Comm.CodegenHelpers.CompletedTask; } private global::System.Threading.Tasks.Task foo14Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { foo14Async(param.Convert<dummy>()); return global::Bond.Comm.CodegenHelpers.CompletedTask; } private global::System.Threading.Tasks.Task foo15Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { foo15Async(param.Convert<global::tests2.OtherBasicTypes>()); return global::Bond.Comm.CodegenHelpers.CompletedTask; } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo21Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<global::Bond.Void>, global::Bond.Comm.IMessage>( foo21Async(param.Convert<global::Bond.Void>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo22Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<global::Bond.Void>, global::Bond.Comm.IMessage>( foo22Async(param.Convert<global::Bond.Void>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo23Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<global::Bond.Void>, global::Bond.Comm.IMessage>( foo23Async(param.Convert<BasicTypes>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo24Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<global::Bond.Void>, global::Bond.Comm.IMessage>( foo24Async(param.Convert<dummy>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo31Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<BasicTypes>, global::Bond.Comm.IMessage>( foo31Async(param.Convert<global::Bond.Void>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo32Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<BasicTypes>, global::Bond.Comm.IMessage>( foo32Async(param.Convert<global::Bond.Void>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo33Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<BasicTypes>, global::Bond.Comm.IMessage>( foo33Async(param.Convert<BasicTypes>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> _rd_foo33Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<BasicTypes>, global::Bond.Comm.IMessage>( _rd_foo33Async(param.Convert<BasicTypes>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo34Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<BasicTypes>, global::Bond.Comm.IMessage>( foo34Async(param.Convert<dummy>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo41Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<dummy>, global::Bond.Comm.IMessage>( foo41Async(param.Convert<global::Bond.Void>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo42Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<dummy>, global::Bond.Comm.IMessage>( foo42Async(param.Convert<global::Bond.Void>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo43Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<dummy>, global::Bond.Comm.IMessage>( foo43Async(param.Convert<BasicTypes>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> foo44Async_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<dummy>, global::Bond.Comm.IMessage>( foo44Async(param.Convert<dummy>(), ct)); } private global::System.Threading.Tasks.Task<global::Bond.Comm.IMessage> cqAsync_Glue(global::Bond.Comm.IMessage param, global::Bond.Comm.ReceiveContext context, global::System.Threading.CancellationToken ct) { return global::Bond.Comm.CodegenHelpers.Upcast<global::Bond.Comm.IMessage<BasicTypes>, global::Bond.Comm.IMessage>( cqAsync(param.Convert<global::Bond.Void>(), ct)); } } } // tests
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using static System.Linq.Expressions.CachedReflectionInfo; namespace System.Linq.Expressions.Compiler { internal partial class LambdaCompiler { private void EmitBlockExpression(Expression expr, CompilationFlags flags) { // emit body Emit((BlockExpression)expr, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsDefaultType)); } private void Emit(BlockExpression node, CompilationFlags flags) { int count = node.ExpressionCount; if (count == 0) { return; } EnterScope(node); CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask; CompilationFlags tailCall = flags & CompilationFlags.EmitAsTailCallMask; for (int index = 0; index < count - 1; index++) { Expression e = node.GetExpression(index); Expression next = node.GetExpression(index + 1); CompilationFlags tailCallFlag; if (tailCall != CompilationFlags.EmitAsNoTail) { var g = next as GotoExpression; if (g != null && (g.Value == null || !Significant(g.Value)) && ReferenceLabel(g.Target).CanReturn) { // Since tail call flags are not passed into EmitTryExpression, CanReturn means the goto will be emitted // as Ret. Therefore we can emit the current expression with tail call. tailCallFlag = CompilationFlags.EmitAsTail; } else { // In the middle of the block. // We may do better here by marking it as Tail if the following expressions are not going to emit any IL. tailCallFlag = CompilationFlags.EmitAsMiddle; } } else { tailCallFlag = CompilationFlags.EmitAsNoTail; } flags = UpdateEmitAsTailCallFlag(flags, tailCallFlag); EmitExpressionAsVoid(e, flags); } // if the type of Block it means this is not a Comma // so we will force the last expression to emit as void. // We don't need EmitAsType flag anymore, should only pass // the EmitTailCall field in flags to emitting the last expression. if (emitAs == CompilationFlags.EmitAsVoidType || node.Type == typeof(void)) { EmitExpressionAsVoid(node.GetExpression(count - 1), tailCall); } else { EmitExpressionAsType(node.GetExpression(count - 1), node.Type, tailCall); } ExitScope(node); } private void EnterScope(object node) { if (HasVariables(node) && (_scope.MergedScopes == null || !_scope.MergedScopes.Contains(node))) { CompilerScope scope; if (!_tree.Scopes.TryGetValue(node, out scope)) { // // Very often, we want to compile nodes as reductions // rather than as IL, but usually they need to allocate // some IL locals. To support this, we allow emitting a // BlockExpression that was not bound by VariableBinder. // This works as long as the variables are only used // locally -- i.e. not closed over. // // User-created blocks will never hit this case; only our // internally reduced nodes will. // scope = new CompilerScope(node, false) { NeedsClosure = _scope.NeedsClosure }; } _scope = scope.Enter(this, _scope); Debug.Assert(_scope.Node == node); } } private static bool HasVariables(object node) { var block = node as BlockExpression; if (block != null) { return block.Variables.Count > 0; } return ((CatchBlock)node).Variable != null; } private void ExitScope(object node) { if (_scope.Node == node) { _scope = _scope.Exit(); } } private void EmitDefaultExpression(Expression expr) { var node = (DefaultExpression)expr; if (node.Type != typeof(void)) { // emit default(T) _ilg.EmitDefault(node.Type, this); } } private void EmitLoopExpression(Expression expr) { LoopExpression node = (LoopExpression)expr; PushLabelBlock(LabelScopeKind.Statement); LabelInfo breakTarget = DefineLabel(node.BreakLabel); LabelInfo continueTarget = DefineLabel(node.ContinueLabel); continueTarget.MarkWithEmptyStack(); EmitExpressionAsVoid(node.Body); _ilg.Emit(OpCodes.Br, continueTarget.Label); PopLabelBlock(LabelScopeKind.Statement); breakTarget.MarkWithEmptyStack(); } #region SwitchExpression private void EmitSwitchExpression(Expression expr, CompilationFlags flags) { SwitchExpression node = (SwitchExpression)expr; if (node.Cases.Count == 0) { // Emit the switch value in case it has side-effects, but as void // since the value is ignored. EmitExpressionAsVoid(node.SwitchValue); // Now if there is a default body, it happens unconditionally. if (node.DefaultBody != null) { EmitExpressionAsType(node.DefaultBody, node.Type, flags); } else { // If there are no cases and no default then the type must be void. // Assert that earlier validation caught any exceptions to that. Debug.Assert(node.Type == typeof(void)); } return; } // Try to emit it as an IL switch. Works for integer types. if (TryEmitSwitchInstruction(node, flags)) { return; } // Try to emit as a hashtable lookup. Works for strings. if (TryEmitHashtableSwitch(node, flags)) { return; } // // Fall back to a series of tests. We need to IL gen instead of // transform the tree to avoid stack overflow on a big switch. // ParameterExpression switchValue = Expression.Parameter(node.SwitchValue.Type, "switchValue"); ParameterExpression testValue = Expression.Parameter(GetTestValueType(node), "testValue"); _scope.AddLocal(this, switchValue); _scope.AddLocal(this, testValue); EmitExpression(node.SwitchValue); _scope.EmitSet(switchValue); // Emit tests var labels = new Label[node.Cases.Count]; var isGoto = new bool[node.Cases.Count]; for (int i = 0, n = node.Cases.Count; i < n; i++) { DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]); foreach (Expression test in node.Cases[i].TestValues) { // Pull the test out into a temp so it runs on the same // stack as the switch. This simplifies spilling. EmitExpression(test); _scope.EmitSet(testValue); Debug.Assert(TypeUtils.AreReferenceAssignable(testValue.Type, test.Type)); EmitExpressionAndBranch(true, Expression.Equal(switchValue, testValue, false, node.Comparison), labels[i]); } } // Define labels Label end = _ilg.DefineLabel(); Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel(); // Emit the case and default bodies EmitSwitchCases(node, labels, isGoto, @default, end, flags); } /// <summary> /// Gets the common test value type of the SwitchExpression. /// </summary> private static Type GetTestValueType(SwitchExpression node) { if (node.Comparison == null) { // If we have no comparison, all right side types must be the // same. return node.Cases[0].TestValues[0].Type; } // Otherwise, get the type from the method. Type result = node.Comparison.GetParametersCached()[1].ParameterType.GetNonRefType(); if (node.IsLifted) { result = result.GetNullableType(); } return result; } private sealed class SwitchLabel { internal readonly decimal Key; internal readonly Label Label; // Boxed version of Key, preserving the original type. internal readonly object Constant; internal SwitchLabel(decimal key, object @constant, Label label) { Key = key; Constant = @constant; Label = label; } } private sealed class SwitchInfo { internal readonly SwitchExpression Node; internal readonly LocalBuilder Value; internal readonly Label Default; internal readonly Type Type; internal readonly bool IsUnsigned; internal readonly bool Is64BitSwitch; internal SwitchInfo(SwitchExpression node, LocalBuilder value, Label @default) { Node = node; Value = value; Default = @default; Type = Node.SwitchValue.Type; IsUnsigned = Type.IsUnsigned(); TypeCode code = Type.GetTypeCode(); Is64BitSwitch = code == TypeCode.UInt64 || code == TypeCode.Int64; } } private static bool FitsInBucket(List<SwitchLabel> buckets, decimal key, int count) { Debug.Assert(key > buckets[buckets.Count - 1].Key); decimal jumpTableSlots = key - buckets[0].Key + 1; if (jumpTableSlots > int.MaxValue) { return false; } // density must be > 50% return (buckets.Count + count) * 2 > jumpTableSlots; } private static void MergeBuckets(List<List<SwitchLabel>> buckets) { while (buckets.Count > 1) { List<SwitchLabel> first = buckets[buckets.Count - 2]; List<SwitchLabel> second = buckets[buckets.Count - 1]; if (!FitsInBucket(first, second[second.Count - 1].Key, second.Count)) { return; } // Merge them first.AddRange(second); buckets.RemoveAt(buckets.Count - 1); } } // Add key to a new or existing bucket private static void AddToBuckets(List<List<SwitchLabel>> buckets, SwitchLabel key) { if (buckets.Count > 0) { List<SwitchLabel> last = buckets[buckets.Count - 1]; if (FitsInBucket(last, key.Key, 1)) { last.Add(key); // we might be able to merge now MergeBuckets(buckets); return; } } // else create a new bucket buckets.Add(new List<SwitchLabel> { key }); } // Determines if the type is an integer we can switch on. private static bool CanOptimizeSwitchType(Type valueType) { // enums & char are allowed switch (valueType.GetTypeCode()) { case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Char: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return true; default: return false; } } // Tries to emit switch as a jmp table private bool TryEmitSwitchInstruction(SwitchExpression node, CompilationFlags flags) { // If we have a comparison, bail if (node.Comparison != null) { return false; } // Make sure the switch value type and the right side type // are types we can optimize Type type = node.SwitchValue.Type; if (!CanOptimizeSwitchType(type) || !TypeUtils.AreEquivalent(type, node.Cases[0].TestValues[0].Type)) { return false; } // Make sure all test values are constant, or we can't emit the // jump table. if (!node.Cases.All(c => c.TestValues.All(t => t is ConstantExpression))) { return false; } // // We can emit the optimized switch, let's do it. // // Build target labels, collect keys. var labels = new Label[node.Cases.Count]; var isGoto = new bool[node.Cases.Count]; var uniqueKeys = new HashSet<decimal>(); var keys = new List<SwitchLabel>(); for (int i = 0; i < node.Cases.Count; i++) { DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]); foreach (ConstantExpression test in node.Cases[i].TestValues) { // Guaranteed to work thanks to CanOptimizeSwitchType. // // Use decimal because it can hold Int64 or UInt64 without // precision loss or signed/unsigned conversions. decimal key = ConvertSwitchValue(test.Value); // Only add each key once. If it appears twice, it's // allowed, but can't be reached. if (uniqueKeys.Add(key)) { keys.Add(new SwitchLabel(key, test.Value, labels[i])); } } } // Sort the keys, and group them into buckets. keys.Sort((x, y) => Math.Sign(x.Key - y.Key)); var buckets = new List<List<SwitchLabel>>(); foreach (SwitchLabel key in keys) { AddToBuckets(buckets, key); } // Emit the switchValue LocalBuilder value = GetLocal(node.SwitchValue.Type); EmitExpression(node.SwitchValue); _ilg.Emit(OpCodes.Stloc, value); // Create end label, and default label if needed Label end = _ilg.DefineLabel(); Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel(); // Emit the switch var info = new SwitchInfo(node, value, @default); EmitSwitchBuckets(info, buckets, 0, buckets.Count - 1); // Emit the case bodies and default EmitSwitchCases(node, labels, isGoto, @default, end, flags); FreeLocal(value); return true; } private static decimal ConvertSwitchValue(object value) { if (value is char) { return (int)(char)value; } return Convert.ToDecimal(value, CultureInfo.InvariantCulture); } /// <summary> /// Creates the label for this case. /// Optimization: if the body is just a goto, and we can branch /// to it, put the goto target directly in the jump table. /// </summary> private void DefineSwitchCaseLabel(SwitchCase @case, out Label label, out bool isGoto) { var jump = @case.Body as GotoExpression; // if it's a goto with no value if (jump != null && jump.Value == null) { // Reference the label from the switch. This will cause us to // analyze the jump target and determine if it is safe. LabelInfo jumpInfo = ReferenceLabel(jump.Target); // If we have are allowed to emit the "branch" opcode, then we // can jump directly there from the switch's jump table. // (Otherwise, we need to emit the goto later as a "leave".) if (jumpInfo.CanBranch) { label = jumpInfo.Label; isGoto = true; return; } } // otherwise, just define a new label label = _ilg.DefineLabel(); isGoto = false; } private void EmitSwitchCases(SwitchExpression node, Label[] labels, bool[] isGoto, Label @default, Label end, CompilationFlags flags) { // Jump to default (to handle the fallthrough case) _ilg.Emit(OpCodes.Br, @default); // Emit the cases for (int i = 0, n = node.Cases.Count; i < n; i++) { // If the body is a goto, we already emitted an optimized // branch directly to it. No need to emit anything else. if (isGoto[i]) { continue; } _ilg.MarkLabel(labels[i]); EmitExpressionAsType(node.Cases[i].Body, node.Type, flags); // Last case doesn't need branch if (node.DefaultBody != null || i < n - 1) { if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) { //The switch case is at the tail of the lambda so //it is safe to emit a Ret. _ilg.Emit(OpCodes.Ret); } else { _ilg.Emit(OpCodes.Br, end); } } } // Default value if (node.DefaultBody != null) { _ilg.MarkLabel(@default); EmitExpressionAsType(node.DefaultBody, node.Type, flags); } _ilg.MarkLabel(end); } private void EmitSwitchBuckets(SwitchInfo info, List<List<SwitchLabel>> buckets, int first, int last) { if (first == last) { EmitSwitchBucket(info, buckets[first]); return; } // Split the buckets into two groups, and use an if test to find // the right bucket. This ensures we'll only need O(lg(B)) tests // where B is the number of buckets int mid = (int)(((long)first + last + 1) / 2); if (first == mid - 1) { EmitSwitchBucket(info, buckets[first]); } else { // If the first half contains more than one, we need to emit an // explicit guard Label secondHalf = _ilg.DefineLabel(); _ilg.Emit(OpCodes.Ldloc, info.Value); EmitConstant(buckets[mid - 1].Last().Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, secondHalf); EmitSwitchBuckets(info, buckets, first, mid - 1); _ilg.MarkLabel(secondHalf); } EmitSwitchBuckets(info, buckets, mid, last); } private void EmitSwitchBucket(SwitchInfo info, List<SwitchLabel> bucket) { // No need for switch if we only have one value if (bucket.Count == 1) { _ilg.Emit(OpCodes.Ldloc, info.Value); EmitConstant(bucket[0].Constant); _ilg.Emit(OpCodes.Beq, bucket[0].Label); return; } // // If we're switching off of Int64/UInt64, we need more guards here // because we'll have to narrow the switch value to an Int32, and // we can't do that unless the value is in the right range. // Label? after = null; if (info.Is64BitSwitch) { after = _ilg.DefineLabel(); _ilg.Emit(OpCodes.Ldloc, info.Value); EmitConstant(bucket.Last().Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, after.Value); _ilg.Emit(OpCodes.Ldloc, info.Value); EmitConstant(bucket[0].Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Blt_Un : OpCodes.Blt, after.Value); } _ilg.Emit(OpCodes.Ldloc, info.Value); // Normalize key decimal key = bucket[0].Key; if (key != 0) { EmitConstant(bucket[0].Constant); _ilg.Emit(OpCodes.Sub); } if (info.Is64BitSwitch) { _ilg.Emit(OpCodes.Conv_I4); } // Collect labels int len = (int)(bucket[bucket.Count - 1].Key - bucket[0].Key + 1); Label[] jmpLabels = new Label[len]; // Initialize all labels to the default int slot = 0; foreach (SwitchLabel label in bucket) { while (key++ != label.Key) { jmpLabels[slot++] = info.Default; } jmpLabels[slot++] = label.Label; } // check we used all keys and filled all slots Debug.Assert(key == bucket[bucket.Count - 1].Key + 1); Debug.Assert(slot == jmpLabels.Length); // Finally, emit the switch instruction _ilg.Emit(OpCodes.Switch, jmpLabels); if (info.Is64BitSwitch) { _ilg.MarkLabel(after.Value); } } private bool TryEmitHashtableSwitch(SwitchExpression node, CompilationFlags flags) { // If we have a comparison other than string equality, bail if (node.Comparison != String_op_Equality_String_String && node.Comparison != String_Equals_String_String) { return false; } // All test values must be constant. int tests = 0; foreach (SwitchCase c in node.Cases) { foreach (Expression t in c.TestValues) { if (!(t is ConstantExpression)) { return false; } tests++; } } // Must have >= 7 labels for it to be worth it. if (tests < 7) { return false; } // If we're in a DynamicMethod, we could just build the dictionary // immediately. But that would cause the two code paths to be more // different than they really need to be. var initializers = new List<ElementInit>(tests); var cases = new ArrayBuilder<SwitchCase>(node.Cases.Count); int nullCase = -1; MethodInfo add = DictionaryOfStringInt32_Add_String_Int32; for (int i = 0, n = node.Cases.Count; i < n; i++) { foreach (ConstantExpression t in node.Cases[i].TestValues) { if (t.Value != null) { initializers.Add(Expression.ElementInit(add, new TrueReadOnlyCollection<Expression>(t, Utils.Constant(i)))); } else { nullCase = i; } } cases.UncheckedAdd(Expression.SwitchCase(node.Cases[i].Body, new TrueReadOnlyCollection<Expression>(Utils.Constant(i)))); } // Create the field to hold the lazily initialized dictionary MemberExpression dictField = CreateLazyInitializedField<Dictionary<string, int>>("dictionarySwitch"); // If we happen to initialize it twice (multithreaded case), it's // not the end of the world. The C# compiler does better here by // emitting a volatile access to the field. Expression dictInit = Expression.Condition( Expression.Equal(dictField, Expression.Constant(null, dictField.Type)), Expression.Assign( dictField, Expression.ListInit( Expression.New( DictionaryOfStringInt32_Ctor_Int32, new TrueReadOnlyCollection<Expression>( Utils.Constant(initializers.Count) ) ), initializers ) ), dictField ); // // Create a tree like: // // switchValue = switchValueExpression; // if (switchValue == null) { // switchIndex = nullCase; // } else { // if (_dictField == null) { // _dictField = new Dictionary<string, int>(count) { { ... }, ... }; // } // if (!_dictField.TryGetValue(switchValue, out switchIndex)) { // switchIndex = -1; // } // } // switch (switchIndex) { // case 0: ... // case 1: ... // ... // default: // } // ParameterExpression switchValue = Expression.Variable(typeof(string), "switchValue"); ParameterExpression switchIndex = Expression.Variable(typeof(int), "switchIndex"); BlockExpression reduced = Expression.Block( new TrueReadOnlyCollection<ParameterExpression>(switchIndex, switchValue), new TrueReadOnlyCollection<Expression>( Expression.Assign(switchValue, node.SwitchValue), Expression.IfThenElse( Expression.Equal(switchValue, Expression.Constant(null, typeof(string))), Expression.Assign(switchIndex, Utils.Constant(nullCase)), Expression.IfThenElse( Expression.Call(dictInit, "TryGetValue", null, switchValue, switchIndex), Utils.Empty, Expression.Assign(switchIndex, Utils.Constant(-1)) ) ), Expression.Switch(node.Type, switchIndex, node.DefaultBody, null, cases.ToReadOnly()) ) ); EmitExpression(reduced, flags); return true; } #endregion private void CheckRethrow() { // Rethrow is only valid inside a catch. for (LabelScopeInfo j = _labelBlock; j != null; j = j.Parent) { if (j.Kind == LabelScopeKind.Catch) { return; } else if (j.Kind == LabelScopeKind.Finally) { // Rethrow from inside finally is not verifiable break; } } throw Error.RethrowRequiresCatch(); } #region TryStatement private void CheckTry() { // Try inside a filter is not verifiable for (LabelScopeInfo j = _labelBlock; j != null; j = j.Parent) { if (j.Kind == LabelScopeKind.Filter) { throw Error.TryNotAllowedInFilter(); } } } private void EmitSaveExceptionOrPop(CatchBlock cb) { if (cb.Variable != null) { // If the variable is present, store the exception // in the variable. _scope.EmitSet(cb.Variable); } else { // Otherwise, pop it off the stack. _ilg.Emit(OpCodes.Pop); } } private void EmitTryExpression(Expression expr) { var node = (TryExpression)expr; CheckTry(); //****************************************************************** // 1. ENTERING TRY //****************************************************************** PushLabelBlock(LabelScopeKind.Try); _ilg.BeginExceptionBlock(); //****************************************************************** // 2. Emit the try statement body //****************************************************************** EmitExpression(node.Body); Type tryType = node.Type; LocalBuilder value = null; if (tryType != typeof(void)) { //store the value of the try body value = GetLocal(tryType); _ilg.Emit(OpCodes.Stloc, value); } //****************************************************************** // 3. Emit the catch blocks //****************************************************************** foreach (CatchBlock cb in node.Handlers) { PushLabelBlock(LabelScopeKind.Catch); // Begin the strongly typed exception block if (cb.Filter == null) { _ilg.BeginCatchBlock(cb.Test); } else { _ilg.BeginExceptFilterBlock(); } EnterScope(cb); EmitCatchStart(cb); // // Emit the catch block body // EmitExpression(cb.Body); if (tryType != typeof(void)) { //store the value of the catch block body _ilg.Emit(OpCodes.Stloc, value); } ExitScope(cb); PopLabelBlock(LabelScopeKind.Catch); } //****************************************************************** // 4. Emit the finally block //****************************************************************** if (node.Finally != null || node.Fault != null) { PushLabelBlock(LabelScopeKind.Finally); if (node.Finally != null) { _ilg.BeginFinallyBlock(); } else { _ilg.BeginFaultBlock(); } // Emit the body EmitExpressionAsVoid(node.Finally ?? node.Fault); _ilg.EndExceptionBlock(); PopLabelBlock(LabelScopeKind.Finally); } else { _ilg.EndExceptionBlock(); } if (tryType != typeof(void)) { _ilg.Emit(OpCodes.Ldloc, value); FreeLocal(value); } PopLabelBlock(LabelScopeKind.Try); } /// <summary> /// Emits the start of a catch block. The exception value that is provided by the /// CLR is stored in the variable specified by the catch block or popped if no /// variable is provided. /// </summary> private void EmitCatchStart(CatchBlock cb) { if (cb.Filter == null) { EmitSaveExceptionOrPop(cb); return; } // emit filter block. Filter blocks are untyped so we need to do // the type check ourselves. Label endFilter = _ilg.DefineLabel(); Label rightType = _ilg.DefineLabel(); // skip if it's not our exception type, but save // the exception if it is so it's available to the // filter _ilg.Emit(OpCodes.Isinst, cb.Test); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Brtrue, rightType); _ilg.Emit(OpCodes.Pop); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br, endFilter); // it's our type, save it and emit the filter. _ilg.MarkLabel(rightType); EmitSaveExceptionOrPop(cb); PushLabelBlock(LabelScopeKind.Filter); EmitExpression(cb.Filter); PopLabelBlock(LabelScopeKind.Filter); // begin the catch, clear the exception, we've // already saved it _ilg.MarkLabel(endFilter); _ilg.BeginCatchBlock(exceptionType: null); _ilg.Emit(OpCodes.Pop); } #endregion } }
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 AprAntecedentePerinatalNacimiento class. /// </summary> [Serializable] public partial class AprAntecedentePerinatalNacimientoCollection : ActiveList<AprAntecedentePerinatalNacimiento, AprAntecedentePerinatalNacimientoCollection> { public AprAntecedentePerinatalNacimientoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprAntecedentePerinatalNacimientoCollection</returns> public AprAntecedentePerinatalNacimientoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprAntecedentePerinatalNacimiento 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 APR_AntecedentePerinatalNacimiento table. /// </summary> [Serializable] public partial class AprAntecedentePerinatalNacimiento : ActiveRecord<AprAntecedentePerinatalNacimiento>, IActiveRecord { #region .ctors and Default Settings public AprAntecedentePerinatalNacimiento() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprAntecedentePerinatalNacimiento(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprAntecedentePerinatalNacimiento(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprAntecedentePerinatalNacimiento(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("APR_AntecedentePerinatalNacimiento", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdAntecedentePerinatalNacimiento = new TableSchema.TableColumn(schema); colvarIdAntecedentePerinatalNacimiento.ColumnName = "idAntecedentePerinatalNacimiento"; colvarIdAntecedentePerinatalNacimiento.DataType = DbType.Int32; colvarIdAntecedentePerinatalNacimiento.MaxLength = 0; colvarIdAntecedentePerinatalNacimiento.AutoIncrement = true; colvarIdAntecedentePerinatalNacimiento.IsNullable = false; colvarIdAntecedentePerinatalNacimiento.IsPrimaryKey = true; colvarIdAntecedentePerinatalNacimiento.IsForeignKey = false; colvarIdAntecedentePerinatalNacimiento.IsReadOnly = false; colvarIdAntecedentePerinatalNacimiento.DefaultSetting = @""; colvarIdAntecedentePerinatalNacimiento.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdAntecedentePerinatalNacimiento); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = false; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarIdAntecedentePerinatal = new TableSchema.TableColumn(schema); colvarIdAntecedentePerinatal.ColumnName = "idAntecedentePerinatal"; colvarIdAntecedentePerinatal.DataType = DbType.Int32; colvarIdAntecedentePerinatal.MaxLength = 0; colvarIdAntecedentePerinatal.AutoIncrement = false; colvarIdAntecedentePerinatal.IsNullable = false; colvarIdAntecedentePerinatal.IsPrimaryKey = false; colvarIdAntecedentePerinatal.IsForeignKey = true; colvarIdAntecedentePerinatal.IsReadOnly = false; colvarIdAntecedentePerinatal.DefaultSetting = @""; colvarIdAntecedentePerinatal.ForeignKeyTableName = "APR_AntecedentePerinatal"; schema.Columns.Add(colvarIdAntecedentePerinatal); TableSchema.TableColumn colvarPeso = new TableSchema.TableColumn(schema); colvarPeso.ColumnName = "Peso"; colvarPeso.DataType = DbType.Double; colvarPeso.MaxLength = 0; colvarPeso.AutoIncrement = false; colvarPeso.IsNullable = false; colvarPeso.IsPrimaryKey = false; colvarPeso.IsForeignKey = false; colvarPeso.IsReadOnly = false; colvarPeso.DefaultSetting = @""; colvarPeso.ForeignKeyTableName = ""; schema.Columns.Add(colvarPeso); TableSchema.TableColumn colvarNacidoVivo = new TableSchema.TableColumn(schema); colvarNacidoVivo.ColumnName = "NacidoVivo"; colvarNacidoVivo.DataType = DbType.Boolean; colvarNacidoVivo.MaxLength = 0; colvarNacidoVivo.AutoIncrement = false; colvarNacidoVivo.IsNullable = false; colvarNacidoVivo.IsPrimaryKey = false; colvarNacidoVivo.IsForeignKey = false; colvarNacidoVivo.IsReadOnly = false; colvarNacidoVivo.DefaultSetting = @""; colvarNacidoVivo.ForeignKeyTableName = ""; schema.Columns.Add(colvarNacidoVivo); TableSchema.TableColumn colvarFechaFallecimiento = new TableSchema.TableColumn(schema); colvarFechaFallecimiento.ColumnName = "FechaFallecimiento"; colvarFechaFallecimiento.DataType = DbType.DateTime; colvarFechaFallecimiento.MaxLength = 0; colvarFechaFallecimiento.AutoIncrement = false; colvarFechaFallecimiento.IsNullable = true; colvarFechaFallecimiento.IsPrimaryKey = false; colvarFechaFallecimiento.IsForeignKey = false; colvarFechaFallecimiento.IsReadOnly = false; colvarFechaFallecimiento.DefaultSetting = @""; colvarFechaFallecimiento.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaFallecimiento); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_AntecedentePerinatalNacimiento",schema); } } #endregion #region Props [XmlAttribute("IdAntecedentePerinatalNacimiento")] [Bindable(true)] public int IdAntecedentePerinatalNacimiento { get { return GetColumnValue<int>(Columns.IdAntecedentePerinatalNacimiento); } set { SetColumnValue(Columns.IdAntecedentePerinatalNacimiento, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int IdEfector { get { return GetColumnValue<int>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("IdAntecedentePerinatal")] [Bindable(true)] public int IdAntecedentePerinatal { get { return GetColumnValue<int>(Columns.IdAntecedentePerinatal); } set { SetColumnValue(Columns.IdAntecedentePerinatal, value); } } [XmlAttribute("Peso")] [Bindable(true)] public double Peso { get { return GetColumnValue<double>(Columns.Peso); } set { SetColumnValue(Columns.Peso, value); } } [XmlAttribute("NacidoVivo")] [Bindable(true)] public bool NacidoVivo { get { return GetColumnValue<bool>(Columns.NacidoVivo); } set { SetColumnValue(Columns.NacidoVivo, value); } } [XmlAttribute("FechaFallecimiento")] [Bindable(true)] public DateTime? FechaFallecimiento { get { return GetColumnValue<DateTime?>(Columns.FechaFallecimiento); } set { SetColumnValue(Columns.FechaFallecimiento, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a AprAntecedentePerinatal ActiveRecord object related to this AprAntecedentePerinatalNacimiento /// /// </summary> public DalSic.AprAntecedentePerinatal AprAntecedentePerinatal { get { return DalSic.AprAntecedentePerinatal.FetchByID(this.IdAntecedentePerinatal); } set { SetColumnValue("idAntecedentePerinatal", value.IdAntecedentePerinatal); } } #endregion //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(int varIdEfector,int varIdAntecedentePerinatal,double varPeso,bool varNacidoVivo,DateTime? varFechaFallecimiento) { AprAntecedentePerinatalNacimiento item = new AprAntecedentePerinatalNacimiento(); item.IdEfector = varIdEfector; item.IdAntecedentePerinatal = varIdAntecedentePerinatal; item.Peso = varPeso; item.NacidoVivo = varNacidoVivo; item.FechaFallecimiento = varFechaFallecimiento; 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 varIdAntecedentePerinatalNacimiento,int varIdEfector,int varIdAntecedentePerinatal,double varPeso,bool varNacidoVivo,DateTime? varFechaFallecimiento) { AprAntecedentePerinatalNacimiento item = new AprAntecedentePerinatalNacimiento(); item.IdAntecedentePerinatalNacimiento = varIdAntecedentePerinatalNacimiento; item.IdEfector = varIdEfector; item.IdAntecedentePerinatal = varIdAntecedentePerinatal; item.Peso = varPeso; item.NacidoVivo = varNacidoVivo; item.FechaFallecimiento = varFechaFallecimiento; 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 IdAntecedentePerinatalNacimientoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdAntecedentePerinatalColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn PesoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn NacidoVivoColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn FechaFallecimientoColumn { get { return Schema.Columns[5]; } } #endregion #region Columns Struct public struct Columns { public static string IdAntecedentePerinatalNacimiento = @"idAntecedentePerinatalNacimiento"; public static string IdEfector = @"idEfector"; public static string IdAntecedentePerinatal = @"idAntecedentePerinatal"; public static string Peso = @"Peso"; public static string NacidoVivo = @"NacidoVivo"; public static string FechaFallecimiento = @"FechaFallecimiento"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using OpenSim.Region.ScriptEngine.Interfaces; using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces { /// <summary> /// To permit region owners to enable the extended scripting functionality /// of OSSL, without allowing malicious scripts to access potentially /// troublesome functions, each OSSL function is assigned a threat level, /// and access to the functions is granted or denied based on a default /// threshold set in OpenSim.ini (which can be overridden for individual /// functions on a case-by-case basis) /// </summary> public enum ThreatLevel { // Not documented, presumably means permanently disabled ? NoAccess = -1, /// <summary> /// Function is no threat at all. It doesn't constitute a threat to /// either users or the system and has no known side effects. /// </summary> None = 0, /// <summary> /// Abuse of this command can cause a nuisance to the region operator, /// such as log message spew. /// </summary> Nuisance = 1, /// <summary> /// Extreme levels of abuse of this function can cause impaired /// functioning of the region, or very gullible users can be tricked /// into experiencing harmless effects. /// </summary> VeryLow = 2, /// <summary> /// Intentional abuse can cause crashes or malfunction under certain /// circumstances, which can be easily rectified; or certain users can /// be tricked into certain situations in an avoidable manner. /// </summary> Low = 3, /// <summary> /// Intentional abuse can cause denial of service and crashes with /// potential of data or state loss; or trusting users can be tricked /// into embarrassing or uncomfortable situations. /// </summary> Moderate = 4, /// <summary> /// Casual abuse can cause impaired functionality or temporary denial /// of service conditions. Intentional abuse can easily cause crashes /// with potential data loss, or can be used to trick experienced and /// cautious users into unwanted situations, or changes global data /// permanently and without undo ability. /// </summary> High = 5, /// <summary> /// Even normal use may, depending on the number of instances, or /// frequency of use, result in severe service impairment or crash /// with loss of data, or can be used to cause unwanted or harmful /// effects on users without giving the user a means to avoid it. /// </summary> VeryHigh = 6, /// <summary> /// Even casual use is a danger to region stability, or function allows /// console or OS command execution, or function allows taking money /// without consent, or allows deletion or modification of user data, /// or allows the compromise of sensitive data by design. /// </summary> Severe = 7 }; public interface IOSSL_Api { void CheckThreatLevel(ThreatLevel level, string function); //OpenSim functions string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams, int timer); string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams, int timer, int alpha); string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams, bool blend, int disp, int timer, int alpha, int face); string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams, int timer); string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams, int timer, int alpha); string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams, bool blend, int disp, int timer, int alpha, int face); LSL_Float osGetTerrainHeight(int x, int y); LSL_Float osTerrainGetHeight(int x, int y); // Deprecated LSL_Integer osSetTerrainHeight(int x, int y, double val); LSL_Integer osTerrainSetHeight(int x, int y, double val); //Deprecated void osTerrainFlush(); int osRegionRestart(double seconds); void osRegionNotice(string msg); bool osConsoleCommand(string Command); void osSetParcelMediaURL(string url); void osSetPrimFloatOnWater(int floatYN); void osSetParcelSIPAddress(string SIPAddress); // Avatar Info Commands string osGetAgentIP(string agent); LSL_List osGetAgents(); // Teleport commands void osTeleportAgent(string agent, string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat); void osTeleportAgent(string agent, int regionX, int regionY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat); void osTeleportAgent(string agent, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat); void osTeleportOwner(string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat); void osTeleportOwner(int regionX, int regionY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat); void osTeleportOwner(LSL_Types.Vector3 position, LSL_Types.Vector3 lookat); // Animation commands void osAvatarPlayAnimation(string avatar, string animation); void osAvatarStopAnimation(string avatar, string animation); #region Attachment commands /// <summary> /// Attach the object containing this script to the avatar that owns it without asking for PERMISSION_ATTACH /// </summary> /// <param name='attachment'>The attachment point. For example, ATTACH_CHEST</param> void osForceAttachToAvatar(int attachment); /// <summary> /// Attach an inventory item in the object containing this script to the avatar that owns it without asking for PERMISSION_ATTACH /// </summary> /// <remarks> /// Nothing happens if the owner is not in the region. /// </remarks> /// <param name='itemName'>Tha name of the item. If this is not found then a warning is said to the owner</param> /// <param name='attachment'>The attachment point. For example, ATTACH_CHEST</param> void osForceAttachToAvatarFromInventory(string itemName, int attachment); /// <summary> /// Attach an inventory item in the object containing this script to any avatar in the region without asking for PERMISSION_ATTACH /// </summary> /// <remarks> /// Nothing happens if the avatar is not in the region. /// </remarks> /// <param name='rawAvatarId'>The UUID of the avatar to which to attach. Nothing happens if this is not a UUID</para> /// <param name='itemName'>The name of the item. If this is not found then a warning is said to the owner</param> /// <param name='attachment'>The attachment point. For example, ATTACH_CHEST</param> void osForceAttachToOtherAvatarFromInventory(string rawAvatarId, string itemName, int attachmentPoint); /// <summary> /// Detach the object containing this script from the avatar it is attached to without checking for PERMISSION_ATTACH /// </summary> /// <remarks>Nothing happens if the object is not attached.</remarks> void osForceDetachFromAvatar(); /// <summary> /// Returns a strided list of the specified attachment points and the number of attachments on those points. /// </summary> /// <param name="avatar">avatar UUID</param> /// <param name="attachmentPoints">list of ATTACH_* constants</param> /// <returns></returns> LSL_List osGetNumberOfAttachments(LSL_Key avatar, LSL_List attachmentPoints); /// <summary> /// Sends a specified message to the specified avatar's attachments on /// the specified attachment points. /// </summary> /// <remarks> /// Behaves as osMessageObject(), without the sending script needing to know the attachment keys in advance. /// </remarks> /// <param name="avatar">avatar UUID</param> /// <param name="message">message string</param> /// <param name="attachmentPoints">list of ATTACH_* constants, or -1 for all attachments. If -1 is specified and OS_ATTACH_MSG_INVERT_POINTS is present in flags, no action is taken.</param> /// <param name="flags">flags further constraining the attachments to deliver the message to.</param> void osMessageAttachments(LSL_Key avatar, string message, LSL_List attachmentPoints, int flags); #endregion //texture draw functions string osMovePen(string drawList, int x, int y); string osDrawLine(string drawList, int startX, int startY, int endX, int endY); string osDrawLine(string drawList, int endX, int endY); string osDrawText(string drawList, string text); string osDrawEllipse(string drawList, int width, int height); string osDrawRectangle(string drawList, int width, int height); string osDrawFilledRectangle(string drawList, int width, int height); string osDrawPolygon(string drawList, LSL_List x, LSL_List y); string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y); string osSetFontName(string drawList, string fontName); string osSetFontSize(string drawList, int fontSize); string osSetPenSize(string drawList, int penSize); string osSetPenColor(string drawList, string color); string osSetPenColour(string drawList, string colour); // Deprecated string osSetPenCap(string drawList, string direction, string type); string osDrawImage(string drawList, int width, int height, string imageUrl); vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize); void osSetStateEvents(int events); double osList2Double(LSL_Types.list src, int index); void osSetRegionWaterHeight(double height); void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour); void osSetEstateSunSettings(bool sunFixed, double sunHour); double osGetCurrentSunHour(); double osGetSunParam(string param); double osSunGetParam(string param); // Deprecated void osSetSunParam(string param, double value); void osSunSetParam(string param, double value); // Deprecated // Wind Module Functions string osWindActiveModelPluginName(); void osSetWindParam(string plugin, string param, LSL_Float value); LSL_Float osGetWindParam(string plugin, string param); // Parcel commands void osParcelJoin(vector pos1, vector pos2); void osParcelSubdivide(vector pos1, vector pos2); void osSetParcelDetails(vector pos, LSL_List rules); void osParcelSetDetails(vector pos, LSL_List rules); // Deprecated string osGetScriptEngineName(); string osGetSimulatorVersion(); LSL_Integer osCheckODE(); string osGetPhysicsEngineType(); Object osParseJSONNew(string JSON); Hashtable osParseJSON(string JSON); void osMessageObject(key objectUUID,string message); void osMakeNotecard(string notecardName, LSL_Types.list contents); string osGetNotecardLine(string name, int line); string osGetNotecard(string name); int osGetNumberOfNotecardLines(string name); string osAvatarName2Key(string firstname, string lastname); string osKey2Name(string id); // Grid Info Functions string osGetGridNick(); string osGetGridName(); string osGetGridLoginURI(); string osGetGridHomeURI(); string osGetGridGatekeeperURI(); string osGetGridCustom(string key); LSL_String osFormatString(string str, LSL_List strings); LSL_List osMatchString(string src, string pattern, int start); LSL_String osReplaceString(string src, string pattern, string replace, int count, int start); // Information about data loaded into the region string osLoadedCreationDate(); string osLoadedCreationTime(); string osLoadedCreationID(); LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules); /// <summary> /// Identical to llCreateLink() but does not require permission from the owner. /// </summary> /// <param name='target'></param> /// <param name='parent'></param> void osForceCreateLink(string target, int parent); /// <summary> /// Identical to llBreakLink() but does not require permission from the owner. /// </summary> /// <param name='linknum'></param> void osForceBreakLink(int linknum); /// <summary> /// Identical to llBreakAllLinks() but does not require permission from the owner. /// </summary> void osForceBreakAllLinks(); /// <summary> /// Check if the given key is an npc /// </summary> /// <param name="npc"></param> /// <returns>TRUE if the key belongs to an npc in the scene. FALSE otherwise.</returns> LSL_Integer osIsNpc(LSL_Key npc); key osNpcCreate(string user, string name, vector position, string notecard); key osNpcCreate(string user, string name, vector position, string notecard, int options); LSL_Key osNpcSaveAppearance(key npc, string notecard); void osNpcLoadAppearance(key npc, string notecard); vector osNpcGetPos(key npc); void osNpcMoveTo(key npc, vector position); void osNpcMoveToTarget(key npc, vector target, int options); /// <summary> /// Get the owner of the NPC /// </summary> /// <param name="npc"></param> /// <returns> /// The owner of the NPC for an owned NPC. The NPC's agent id for an unowned NPC. UUID.Zero if the key is not an npc. /// </returns> LSL_Key osNpcGetOwner(key npc); rotation osNpcGetRot(key npc); void osNpcSetRot(LSL_Key npc, rotation rot); void osNpcStopMoveToTarget(LSL_Key npc); void osNpcSay(key npc, string message); void osNpcSay(key npc, int channel, string message); void osNpcShout(key npc, int channel, string message); void osNpcSit(key npc, key target, int options); void osNpcStand(LSL_Key npc); void osNpcRemove(key npc); void osNpcPlayAnimation(LSL_Key npc, string animation); void osNpcStopAnimation(LSL_Key npc, string animation); void osNpcTouch(LSL_Key npcLSL_Key, LSL_Key object_key, LSL_Integer link_num); void osNpcWhisper(key npc, int channel, string message); LSL_Key osOwnerSaveAppearance(string notecard); LSL_Key osAgentSaveAppearance(key agentId, string notecard); key osGetGender(LSL_Key rawAvatarId); key osGetMapTexture(); key osGetRegionMapTexture(string regionName); LSL_List osGetRegionStats(); vector osGetRegionSize(); int osGetSimulatorMemory(); void osKickAvatar(string FirstName,string SurName,string alert); void osSetSpeed(string UUID, LSL_Float SpeedModifier); LSL_Float osGetHealth(string avatar); void osCauseHealing(string avatar, double healing); void osCauseDamage(string avatar, double damage); void osForceOtherSit(string avatar); void osForceOtherSit(string avatar, string target); LSL_List osGetPrimitiveParams(LSL_Key prim, LSL_List rules); void osSetPrimitiveParams(LSL_Key prim, LSL_List rules); void osSetProjectionParams(bool projection, LSL_Key texture, double fov, double focus, double amb); void osSetProjectionParams(LSL_Key prim, bool projection, LSL_Key texture, double fov, double focus, double amb); LSL_List osGetAvatarList(); LSL_String osUnixTimeToTimestamp(long time); LSL_String osGetInventoryDesc(string item); LSL_Integer osInviteToGroup(LSL_Key agentId); LSL_Integer osEjectFromGroup(LSL_Key agentId); void osSetTerrainTexture(int level, LSL_Key texture); void osSetTerrainTextureHeight(int corner, double low, double high); /// <summary> /// Checks if thing is a UUID. /// </summary> /// <param name="thing"></param> /// <returns>1 if thing is a valid UUID, 0 otherwise</returns> LSL_Integer osIsUUID(string thing); /// <summary> /// Wraps to Math.Min() /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> LSL_Float osMin(double a, double b); /// <summary> /// Wraps to Math.max() /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> LSL_Float osMax(double a, double b); /// <summary> /// Get the key of the object that rezzed this object. /// </summary> /// <returns>Rezzing object key or NULL_KEY if rezzed by agent or otherwise unknown.</returns> LSL_Key osGetRezzingObject(); /// <summary> /// Sets the response type for an HTTP request/response /// </summary> /// <returns></returns> void osSetContentType(LSL_Key id, string type); /// <summary> /// Attempts to drop an attachment to the ground /// </summary> void osDropAttachment(); /// <summary> /// Attempts to drop an attachment to the ground while bypassing the script permissions /// </summary> void osForceDropAttachment(); /// <summary> /// Attempts to drop an attachment at the specified coordinates. /// </summary> /// <param name="pos"></param> /// <param name="rot"></param> void osDropAttachmentAt(vector pos, rotation rot); /// <summary> /// Attempts to drop an attachment at the specified coordinates while bypassing the script permissions /// </summary> /// <param name="pos"></param> /// <param name="rot"></param> void osForceDropAttachmentAt(vector pos, rotation rot); /// <summary> /// Identical to llListen except for a bitfield which indicates which /// string parameters should be parsed as regex patterns. /// </summary> /// <param name="channelID"></param> /// <param name="name"></param> /// <param name="ID"></param> /// <param name="msg"></param> /// <param name="regexBitfield"> /// OS_LISTEN_REGEX_NAME /// OS_LISTEN_REGEX_MESSAGE /// </param> /// <returns></returns> LSL_Integer osListenRegex(int channelID, string name, string ID, string msg, int regexBitfield); /// <summary> /// Wraps to bool Regex.IsMatch(string input, string pattern) /// </summary> /// <param name="input">string to test for match</param> /// <param name="regex">string to use as pattern</param> /// <returns>boolean</returns> LSL_Integer osRegexIsMatch(string input, string pattern); } }
// 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 gagr = Google.Api.Gax.ResourceNames; using lro = Google.LongRunning; 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.Domains.V1Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedDomainsClientTest { [xunit::FactAttribute] public void SearchDomainsRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomains(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse response = client.SearchDomains(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SearchDomainsRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomainsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchDomainsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse responseCallSettings = await client.SearchDomainsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SearchDomainsResponse responseCancellationToken = await client.SearchDomainsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SearchDomains() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomains(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse response = client.SearchDomains(request.Location, request.Query); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SearchDomainsAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomainsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchDomainsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse responseCallSettings = await client.SearchDomainsAsync(request.Location, request.Query, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SearchDomainsResponse responseCancellationToken = await client.SearchDomainsAsync(request.Location, request.Query, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SearchDomainsResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomains(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse response = client.SearchDomains(request.LocationAsLocationName, request.Query); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SearchDomainsResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomainsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchDomainsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse responseCallSettings = await client.SearchDomainsAsync(request.LocationAsLocationName, request.Query, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SearchDomainsResponse responseCancellationToken = await client.SearchDomainsAsync(request.LocationAsLocationName, request.Query, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveRegisterParametersRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse response = client.RetrieveRegisterParameters(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveRegisterParametersRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveRegisterParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse responseCallSettings = await client.RetrieveRegisterParametersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveRegisterParametersResponse responseCancellationToken = await client.RetrieveRegisterParametersAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveRegisterParameters() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse response = client.RetrieveRegisterParameters(request.Location, request.DomainName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveRegisterParametersAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveRegisterParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse responseCallSettings = await client.RetrieveRegisterParametersAsync(request.Location, request.DomainName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveRegisterParametersResponse responseCancellationToken = await client.RetrieveRegisterParametersAsync(request.Location, request.DomainName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveRegisterParametersResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse response = client.RetrieveRegisterParameters(request.LocationAsLocationName, request.DomainName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveRegisterParametersResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveRegisterParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse responseCallSettings = await client.RetrieveRegisterParametersAsync(request.LocationAsLocationName, request.DomainName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveRegisterParametersResponse responseCancellationToken = await client.RetrieveRegisterParametersAsync(request.LocationAsLocationName, request.DomainName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveTransferParametersRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse response = client.RetrieveTransferParameters(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveTransferParametersRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveTransferParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse responseCallSettings = await client.RetrieveTransferParametersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveTransferParametersResponse responseCancellationToken = await client.RetrieveTransferParametersAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveTransferParameters() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse response = client.RetrieveTransferParameters(request.Location, request.DomainName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveTransferParametersAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveTransferParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse responseCallSettings = await client.RetrieveTransferParametersAsync(request.Location, request.DomainName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveTransferParametersResponse responseCancellationToken = await client.RetrieveTransferParametersAsync(request.Location, request.DomainName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveTransferParametersResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse response = client.RetrieveTransferParameters(request.LocationAsLocationName, request.DomainName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveTransferParametersResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveTransferParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse responseCallSettings = await client.RetrieveTransferParametersAsync(request.LocationAsLocationName, request.DomainName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveTransferParametersResponse responseCancellationToken = await client.RetrieveTransferParametersAsync(request.LocationAsLocationName, request.DomainName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRegistrationRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration response = client.GetRegistration(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRegistrationRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Registration>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration responseCallSettings = await client.GetRegistrationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Registration responseCancellationToken = await client.GetRegistrationAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRegistration() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration response = client.GetRegistration(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRegistrationAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Registration>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration responseCallSettings = await client.GetRegistrationAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Registration responseCancellationToken = await client.GetRegistrationAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRegistrationResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration response = client.GetRegistration(request.RegistrationName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRegistrationResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Registration>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration responseCallSettings = await client.GetRegistrationAsync(request.RegistrationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Registration responseCancellationToken = await client.GetRegistrationAsync(request.RegistrationName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveAuthorizationCodeRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.RetrieveAuthorizationCode(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveAuthorizationCodeRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.RetrieveAuthorizationCodeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.RetrieveAuthorizationCodeAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveAuthorizationCode() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.RetrieveAuthorizationCode(request.Registration); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveAuthorizationCodeAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.RetrieveAuthorizationCodeAsync(request.Registration, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.RetrieveAuthorizationCodeAsync(request.Registration, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveAuthorizationCodeResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.RetrieveAuthorizationCode(request.RegistrationAsRegistrationName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveAuthorizationCodeResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.RetrieveAuthorizationCodeAsync(request.RegistrationAsRegistrationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.RetrieveAuthorizationCodeAsync(request.RegistrationAsRegistrationName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ResetAuthorizationCodeRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.ResetAuthorizationCode(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ResetAuthorizationCodeRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.ResetAuthorizationCodeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.ResetAuthorizationCodeAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ResetAuthorizationCode() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.ResetAuthorizationCode(request.Registration); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ResetAuthorizationCodeAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.ResetAuthorizationCodeAsync(request.Registration, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.ResetAuthorizationCodeAsync(request.Registration, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ResetAuthorizationCodeResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.ResetAuthorizationCode(request.RegistrationAsRegistrationName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ResetAuthorizationCodeResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.ResetAuthorizationCodeAsync(request.RegistrationAsRegistrationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.ResetAuthorizationCodeAsync(request.RegistrationAsRegistrationName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; using System.Globalization; using NUnit.Framework.Constraints; namespace NUnit.Framework { /// <summary> /// TextMessageWriter writes constraint descriptions and messages /// in displayable form as a text stream. It tailors the display /// of individual message components to form the standard message /// format of NUnit assertion failure messages. /// </summary> public class TextMessageWriter : MessageWriter { #region Message Formats and Constants private static readonly int DEFAULT_LINE_LENGTH = 78; // Prefixes used in all failure messages. All must be the same // length, which is held in the PrefixLength field. Should not // contain any tabs or newline characters. /// <summary> /// Prefix used for the expected value line of a message /// </summary> public static readonly string Pfx_Expected = " Expected: "; /// <summary> /// Prefix used for the actual value line of a message /// </summary> public static readonly string Pfx_Actual = " But was: "; /// <summary> /// Length of a message prefix /// </summary> public static readonly int PrefixLength = Pfx_Expected.Length; private static readonly string Fmt_Connector = " {0} "; private static readonly string Fmt_Predicate = "{0} "; //private static readonly string Fmt_Label = "{0}"; private static readonly string Fmt_Modifier = ", {0}"; private static readonly string Fmt_Null = "null"; private static readonly string Fmt_EmptyString = "<string.Empty>"; private static readonly string Fmt_EmptyCollection = "<empty>"; private static readonly string Fmt_String = "\"{0}\""; private static readonly string Fmt_Char = "'{0}'"; private static readonly string Fmt_DateTime = "yyyy-MM-dd HH:mm:ss.fff"; private static readonly string Fmt_ValueType = "{0}"; private static readonly string Fmt_Default = "<{0}>"; #endregion private int maxLineLength = DEFAULT_LINE_LENGTH; #region Constructors /// <summary> /// Construct a TextMessageWriter /// </summary> public TextMessageWriter() { } /// <summary> /// Construct a TextMessageWriter, specifying a user message /// and optional formatting arguments. /// </summary> /// <param name="userMessage"></param> /// <param name="args"></param> public TextMessageWriter(string userMessage, params object[] args) { if ( userMessage != null && userMessage != string.Empty) this.WriteMessageLine(userMessage, args); } #endregion #region Properties /// <summary> /// Gets or sets the maximum line length for this writer /// </summary> public override int MaxLineLength { get { return maxLineLength; } set { maxLineLength = value; } } #endregion #region Public Methods - High Level /// <summary> /// Method to write single line message with optional args, usually /// written to precede the general failure message, at a givel /// indentation level. /// </summary> /// <param name="level">The indentation level of the message</param> /// <param name="message">The message to be written</param> /// <param name="args">Any arguments used in formatting the message</param> public override void WriteMessageLine(int level, string message, params object[] args) { if (message != null) { while (level-- >= 0) Write(" "); if (args != null && args.Length > 0) message = string.Format(message, args); WriteLine(message); } } /// <summary> /// Display Expected and Actual lines for a constraint. This /// is called by MessageWriter's default implementation of /// WriteMessageTo and provides the generic two-line display. /// </summary> /// <param name="constraint">The constraint that failed</param> public override void DisplayDifferences(Constraint constraint) { WriteExpectedLine(constraint); WriteActualLine(constraint); } /// <summary> /// Display Expected and Actual lines for given values. This /// method may be called by constraints that need more control over /// the display of actual and expected values than is provided /// by the default implementation. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> public override void DisplayDifferences(object expected, object actual) { WriteExpectedLine(expected); WriteActualLine(actual); } /// <summary> /// Display Expected and Actual lines for given values, including /// a tolerance value on the expected line. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> /// <param name="tolerance">The tolerance within which the test was made</param> public override void DisplayDifferences(object expected, object actual, Tolerance tolerance) { WriteExpectedLine(expected, tolerance); WriteActualLine(actual); } /// <summary> /// Display the expected and actual string values on separate lines. /// If the mismatch parameter is >=0, an additional line is displayed /// line containing a caret that points to the mismatch point. /// </summary> /// <param name="expected">The expected string value</param> /// <param name="actual">The actual string value</param> /// <param name="mismatch">The point at which the strings don't match or -1</param> /// <param name="ignoreCase">If true, case is ignored in string comparisons</param> /// <param name="clipping">If true, clip the strings to fit the max line length</param> public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping) { // Maximum string we can display without truncating int maxDisplayLength = MaxLineLength - PrefixLength // Allow for prefix - 2; // 2 quotation marks if ( clipping ) MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch); expected = MsgUtils.EscapeControlChars(expected); actual = MsgUtils.EscapeControlChars(actual); // The mismatch position may have changed due to clipping or white space conversion mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase); Write( Pfx_Expected ); WriteExpectedValue( expected ); if ( ignoreCase ) WriteModifier( "ignoring case" ); WriteLine(); WriteActualLine( actual ); //DisplayDifferences(expected, actual); if (mismatch >= 0) WriteCaretLine(mismatch); } #endregion #region Public Methods - Low Level /// <summary> /// Writes the text for a connector. /// </summary> /// <param name="connector">The connector.</param> public override void WriteConnector(string connector) { Write(Fmt_Connector, connector); } /// <summary> /// Writes the text for a predicate. /// </summary> /// <param name="predicate">The predicate.</param> public override void WritePredicate(string predicate) { Write(Fmt_Predicate, predicate); } //public override void WriteLabel(string label) //{ // Write(Fmt_Label, label); //} /// <summary> /// Write the text for a modifier. /// </summary> /// <param name="modifier">The modifier.</param> public override void WriteModifier(string modifier) { Write(Fmt_Modifier, modifier); } /// <summary> /// Writes the text for an expected value. /// </summary> /// <param name="expected">The expected value.</param> public override void WriteExpectedValue(object expected) { WriteValue(expected); } /// <summary> /// Writes the text for an actual value. /// </summary> /// <param name="actual">The actual value.</param> public override void WriteActualValue(object actual) { WriteValue(actual); } /// <summary> /// Writes the text for a generalized value. /// </summary> /// <param name="val">The value.</param> public override void WriteValue(object val) { if (val == null) Write(Fmt_Null); else if (val.GetType().IsArray) WriteArray((Array)val); else if (val is string) WriteString((string)val); else if (val is IEnumerable) WriteCollectionElements((IEnumerable)val, 0, 10); else if (val is char) WriteChar((char)val); else if (val is double) WriteDouble((double)val); else if (val is float) WriteFloat((float)val); else if (val is decimal) WriteDecimal((decimal)val); else if (val is DateTime) WriteDateTime((DateTime)val); else if (val.GetType().IsValueType) Write(Fmt_ValueType, val); else Write(Fmt_Default, val); } /// <summary> /// Writes the text for a collection value, /// starting at a particular point, to a max length /// </summary> /// <param name="collection">The collection containing elements to write.</param> /// <param name="start">The starting point of the elements to write</param> /// <param name="max">The maximum number of elements to write</param> public override void WriteCollectionElements(IEnumerable collection, int start, int max) { int count = 0; int index = 0; foreach (object obj in collection) { if ( index++ >= start) { if (++count > max) break; Write(count == 1 ? "< " : ", "); WriteValue(obj); } } if (count == 0) { Write(Fmt_EmptyCollection); return; } if (count > max) Write("..."); Write(" >"); } private void WriteArray(Array array) { if ( array.Length == 0 ) { Write( Fmt_EmptyCollection ); return; } int rank = array.Rank; int[] products = new int[rank]; for (int product = 1, r = rank; --r >= 0; ) products[r] = product *= array.GetLength(r); int count = 0; foreach (object obj in array) { if (count > 0) Write(", "); bool startSegment = false; for (int r = 0; r < rank; r++) { startSegment = startSegment || count % products[r] == 0; if (startSegment) Write("< "); } WriteValue(obj); ++count; bool nextSegment = false; for (int r = 0; r < rank; r++) { nextSegment = nextSegment || count % products[r] == 0; if (nextSegment) Write(" >"); } } } private void WriteString(string s) { if (s == string.Empty) Write(Fmt_EmptyString); else Write(Fmt_String, s); } private void WriteChar(char c) { Write(Fmt_Char, c); } private void WriteDouble(double d) { if (double.IsNaN(d) || double.IsInfinity(d)) Write(d); else { string s = d.ToString("G17", CultureInfo.InvariantCulture); if (s.IndexOf('.') > 0) Write(s + "d"); else Write(s + ".0d"); } } private void WriteFloat(float f) { if (float.IsNaN(f) || float.IsInfinity(f)) Write(f); else { string s = f.ToString("G9", CultureInfo.InvariantCulture); if (s.IndexOf('.') > 0) Write(s + "f"); else Write(s + ".0f"); } } private void WriteDecimal(Decimal d) { Write(d.ToString("G29", CultureInfo.InvariantCulture) + "m"); } private void WriteDateTime(DateTime dt) { Write(dt.ToString(Fmt_DateTime, CultureInfo.InvariantCulture)); } #endregion #region Helper Methods /// <summary> /// Write the generic 'Expected' line for a constraint /// </summary> /// <param name="constraint">The constraint that failed</param> private void WriteExpectedLine(Constraint constraint) { Write(Pfx_Expected); constraint.WriteDescriptionTo(this); WriteLine(); } /// <summary> /// Write the generic 'Expected' line for a given value /// </summary> /// <param name="expected">The expected value</param> private void WriteExpectedLine(object expected) { WriteExpectedLine(expected, null); } /// <summary> /// Write the generic 'Expected' line for a given value /// and tolerance. /// </summary> /// <param name="expected">The expected value</param> /// <param name="tolerance">The tolerance within which the test was made</param> private void WriteExpectedLine(object expected, Tolerance tolerance) { Write(Pfx_Expected); WriteExpectedValue(expected); if (tolerance != null && !tolerance.IsEmpty) { WriteConnector("+/-"); WriteExpectedValue(tolerance.Value); if (tolerance.Mode != ToleranceMode.Linear) Write(" {0}", tolerance.Mode); } WriteLine(); } /// <summary> /// Write the generic 'Actual' line for a constraint /// </summary> /// <param name="constraint">The constraint for which the actual value is to be written</param> private void WriteActualLine(Constraint constraint) { Write(Pfx_Actual); constraint.WriteActualValueTo(this); WriteLine(); } /// <summary> /// Write the generic 'Actual' line for a given value /// </summary> /// <param name="actual">The actual value causing a failure</param> private void WriteActualLine(object actual) { Write(Pfx_Actual); WriteActualValue(actual); WriteLine(); } private void WriteCaretLine(int mismatch) { // We subtract 2 for the initial 2 blanks and add back 1 for the initial quote WriteLine(" {0}^", new string('-', PrefixLength + mismatch - 2 + 1)); } #endregion } }
#nullable disable using System.Collections; using System.Collections.Specialized; namespace Meziantou.Framework.Html; public sealed class HtmlNodeList : IList<HtmlNode>, INotifyCollectionChanged, IList, IReadOnlyList<HtmlNode> { private readonly List<HtmlNode> _list = new(); private readonly HtmlNode _parent; public event NotifyCollectionChangedEventHandler CollectionChanged; internal HtmlNodeList(HtmlNode parent) { _parent = parent; } private void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { _parent.ClearCaches(); CollectionChanged?.Invoke(this, e); } public HtmlNode this[string name] { get { if (name == null) throw new ArgumentNullException(nameof(name)); return _list.Find(n => n.Name.EqualsIgnoreCase(name)); } } public HtmlNode this[string localName, string namespaceURI] { get { if (localName == null) throw new ArgumentNullException(nameof(localName)); if (namespaceURI == null) throw new ArgumentNullException(nameof(namespaceURI)); return _list.Find(a => localName.EqualsIgnoreCase(a.LocalName) && a.NamespaceURI != null && string.Equals(namespaceURI, a.NamespaceURI, StringComparison.Ordinal)); } } public HtmlNode this[int index] { get => _list[index]; set { if (value == _list[index]) return; var oldItem = _list[index]; _list[index] = value; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, oldItem)); } } public void Replace(HtmlNode newChild!!, HtmlNode oldChild!!) { if (newChild.ParentNode != null) throw new ArgumentException(message: null, nameof(newChild)); var index = _list.IndexOf(oldChild); if (index >= 0) { if (oldChild.ParentNode != _parent) throw new ArgumentException(message: null, nameof(oldChild)); HtmlDocument.RemoveIntrinsicElement(oldChild.OwnerDocument, oldChild as HtmlElement); oldChild.ParentNode = null; _list.RemoveAt(index); } else { throw new ArgumentException(message: null, nameof(oldChild)); } _list.Insert(index, newChild); newChild.ParentNode = _parent; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newChild, oldChild)); } internal void RemoveAllNoCheck() { _list.Clear(); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } public void RemoveAll() { foreach (var node in _list) { HtmlDocument.RemoveIntrinsicElement(node.OwnerDocument, node as HtmlElement); if (node.ParentNode != _parent) throw new InvalidOperationException(); node.ParentNode = null; } RemoveAllNoCheck(); } public void Insert(int index, HtmlNode item!!) { if (item.ParentNode != null) throw new ArgumentException(message: null, nameof(item)); HtmlDocument.RemoveIntrinsicElement(item.OwnerDocument, item as HtmlElement); _list.Insert(index, item); item.ParentNode = _parent; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); } public void AddRange(IEnumerable<HtmlNode> nodes) { if (nodes == null) return; foreach (var node in nodes) { Add(node); } } internal void AddNoCheck(HtmlNode node) { _list.Add(node); node.ParentNode = _parent; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, node)); } public void Add(HtmlNode item!!) { if (item.ParentNode != null) throw new ArgumentException(message: null, nameof(item)); AddNoCheck(item); } public bool RemoveAt(int index) { if (index < 0 || index >= _list.Count) return false; var node = _list[index]; if (node.ParentNode != _parent) throw new ArgumentException(message: null, nameof(index)); HtmlDocument.RemoveIntrinsicElement(node.OwnerDocument, node as HtmlElement); node.ParentNode = null; _list.RemoveAt(index); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, node, index)); return true; } public bool Remove(HtmlNode item!!) { var index = _list.IndexOf(item); if (index < 0) return false; var existing = _list[index]; if (existing.ParentNode != _parent) throw new ArgumentException(message: null, nameof(item)); _list.RemoveAt(index); HtmlDocument.RemoveIntrinsicElement(item.OwnerDocument, item as HtmlElement); item.ParentNode = null; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item)); return true; } public int Count => _list.Count; public int IndexOf(HtmlNode item) => _list.IndexOf(item); public bool Contains(HtmlNode item) => IndexOf(item) >= 0; public void CopyTo(HtmlNode[] array, int arrayIndex) => _list.CopyTo(array, arrayIndex); public IEnumerator<HtmlNode> GetEnumerator() => _list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); bool ICollection<HtmlNode>.IsReadOnly => false; void ICollection<HtmlNode>.Clear() => RemoveAll(); int IList.Add(object value) { var count = Count; Add((HtmlNode)value); return count; } void IList.Clear() => RemoveAll(); bool IList.Contains(object value) => Contains((HtmlNode)value); int IList.IndexOf(object value) => IndexOf((HtmlNode)value); void IList.Insert(int index, object value) => Insert(index, (HtmlNode)value); bool IList.IsFixedSize => false; bool IList.IsReadOnly => false; void IList.Remove(object value) => Remove((HtmlNode)value); void IList.RemoveAt(int index) => RemoveAt(index); void IList<HtmlNode>.RemoveAt(int index) => RemoveAt(index); void ICollection.CopyTo(Array array, int index) => ((ICollection)_list).CopyTo(array, index); bool ICollection.IsSynchronized => ((ICollection)_list).IsSynchronized; object ICollection.SyncRoot => ((ICollection)_list).SyncRoot; object IList.this[int index] { get => this[index]; set => this[index] = (HtmlNode)value; } }
// ByteFX.Data data access components for .Net // Copyright (C) 2002-2003 ByteFX, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.IO; using System.Runtime.InteropServices; namespace ByteFX.Data.Common { /// <summary> /// Summary description for API. /// </summary> internal class NamedPipeStream : Stream { [DllImport("kernel32.dll", EntryPoint="CreateFile", SetLastError=true)] private static extern IntPtr CreateFile(String lpFileName, UInt32 dwDesiredAccess, UInt32 dwShareMode, IntPtr lpSecurityAttributes, UInt32 dwCreationDisposition, UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile); [DllImport("kernel32.dll", EntryPoint="PeekNamedPipe", SetLastError=true)] private static extern bool PeekNamedPipe( IntPtr handle, byte[] buffer, uint nBufferSize, ref uint bytesRead, ref uint bytesAvail, ref uint BytesLeftThisMessage); [DllImport("kernel32.dll", SetLastError=true)] private static extern bool ReadFile( IntPtr handle, byte[] buffer, uint toRead, ref uint read, IntPtr lpOverLapped); [DllImport("kernel32.dll", SetLastError=true)] private static extern bool WriteFile( IntPtr handle, byte[] buffer, uint count, ref uint written, IntPtr lpOverlapped ); [DllImport("kernel32.dll", SetLastError=true)] private static extern bool CloseHandle( IntPtr handle ); [DllImport("kernel32.dll", SetLastError=true)] private static extern bool FlushFileBuffers( IntPtr handle ); //Constants for dwDesiredAccess: private const UInt32 GENERIC_READ = 0x80000000; private const UInt32 GENERIC_WRITE = 0x40000000; //Constants for return value: private const Int32 INVALID_HANDLE_VALUE = -1; //Constants for dwFlagsAndAttributes: private const UInt32 FILE_FLAG_OVERLAPPED = 0x40000000; private const UInt32 FILE_FLAG_NO_BUFFERING = 0x20000000; //Constants for dwCreationDisposition: private const UInt32 OPEN_EXISTING = 3; IntPtr _handle; FileAccess _mode; public NamedPipeStream(string host, FileAccess mode) { _handle = IntPtr.Zero; Open(host, mode); } public void Open( string host, FileAccess mode ) { _mode = mode; uint pipemode = 0; if ((mode & FileAccess.Read) > 0) pipemode |= GENERIC_READ; if ((mode & FileAccess.Write) > 0) pipemode |= GENERIC_WRITE; _handle = CreateFile( host, pipemode, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero ); } public bool DataAvailable { get { uint bytesRead=0, avail=0, thismsg=0; bool result = PeekNamedPipe( _handle, null, 0, ref bytesRead, ref avail, ref thismsg ); return (result == true && avail > 0); } } public override bool CanRead { get { return (_mode & FileAccess.Read) > 0; } } public override bool CanWrite { get { return (_mode & FileAccess.Write) > 0; } } public override bool CanSeek { get { throw new NotSupportedException("NamedPipeStream does not support seeking"); } } public override long Length { get { throw new NotSupportedException("NamedPipeStream does not support seeking"); } } public override long Position { get { throw new NotSupportedException("NamedPipeStream does not support seeking"); } set { } } public override void Flush() { if (_handle == IntPtr.Zero) throw new ObjectDisposedException("NamedPipeStream", "The stream has already been closed"); FlushFileBuffers(_handle); } public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer", "The buffer to read into cannot be null"); if (buffer.Length < (offset + count)) throw new ArgumentException("Buffer is not large enough to hold requested data", "buffer"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", offset, "Offset cannot be negative"); if (count < 0) throw new ArgumentOutOfRangeException("count", count, "Count cannot be negative"); if (! CanRead) throw new NotSupportedException("The stream does not support reading"); if (_handle == IntPtr.Zero) throw new ObjectDisposedException("NamedPipeStream", "The stream has already been closed"); // first read the data into an internal buffer since ReadFile cannot read into a buf at // a specified offset uint read=0; byte[] buf = new Byte[count]; ReadFile( _handle, buf, (uint)count, ref read, IntPtr.Zero ); for (int x=0; x < read; x++) { buffer[offset+x] = buf[x]; } return (int)read; } public override void Close() { CloseHandle(_handle); _handle = IntPtr.Zero; } public override void SetLength(long length) { throw new NotSupportedException("NamedPipeStream doesn't support SetLength"); } public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer", "The buffer to write into cannot be null"); if (buffer.Length < (offset + count)) throw new ArgumentException("Buffer does not contain amount of requested data", "buffer"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", offset, "Offset cannot be negative"); if (count < 0) throw new ArgumentOutOfRangeException("count", count, "Count cannot be negative"); if (! CanWrite) throw new NotSupportedException("The stream does not support writing"); if (_handle == IntPtr.Zero) throw new ObjectDisposedException("NamedPipeStream", "The stream has already been closed"); // copy data to internal buffer to allow writing from a specified offset byte[] buf = new Byte[count]; for (int x=0; x < count; x++) { buf[x] = buffer[offset+x]; } uint written=0; bool result = WriteFile( _handle, buf, (uint)count, ref written, IntPtr.Zero ); if (! result) throw new IOException("Writing to the stream failed"); if (written < count) throw new IOException("Unable to write entire buffer to stream"); } public override long Seek( long offset, SeekOrigin origin ) { throw new NotSupportedException("NamedPipeStream doesn't support seeking"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Castle.DynamicProxy; using Castle.MicroKernel; using Castle.MicroKernel.Registration; using Castle.Windsor; using Castle.Windsor.Installer; using Castle.Windsor.Proxy; namespace Abp.Dependency { /// <summary> /// This class is used to directly perform dependency injection tasks. /// </summary> public class IocManager : IIocManager { /// <summary> /// The Singleton instance. /// </summary> public static IocManager Instance { get; private set; } /// <summary> /// Singletone instance for Castle ProxyGenerator. /// From Castle.Core documentation it is highly recomended to use single instance of ProxyGenerator to avoid memoryleaks and performance issues /// Follow next links for more details: /// <a href="https://github.com/castleproject/Core/blob/master/docs/dynamicproxy.md">Castle.Core documentation</a>, /// <a href="http://kozmic.net/2009/07/05/castle-dynamic-proxy-tutorial-part-xii-caching/">Article</a> /// </summary> private static readonly ProxyGenerator ProxyGeneratorInstance = new ProxyGenerator(); /// <summary> /// Reference to the Castle Windsor Container. /// </summary> public IWindsorContainer IocContainer { get; private set; } /// <summary> /// List of all registered conventional registrars. /// </summary> private readonly List<IConventionalDependencyRegistrar> _conventionalRegistrars; static IocManager() { Instance = new IocManager(); } /// <summary> /// Creates a new <see cref="IocManager"/> object. /// Normally, you don't directly instantiate an <see cref="IocManager"/>. /// This may be useful for test purposes. /// </summary> public IocManager() { IocContainer = CreateContainer(); _conventionalRegistrars = new List<IConventionalDependencyRegistrar>(); //Register self! IocContainer.Register( Component .For<IocManager, IIocManager, IIocRegistrar, IIocResolver>() .Instance(this) ); } protected virtual IWindsorContainer CreateContainer() { return new WindsorContainer(new DefaultProxyFactory(ProxyGeneratorInstance)); } /// <summary> /// Adds a dependency registrar for conventional registration. /// </summary> /// <param name="registrar">dependency registrar</param> public void AddConventionalRegistrar(IConventionalDependencyRegistrar registrar) { _conventionalRegistrars.Add(registrar); } /// <summary> /// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method. /// </summary> /// <param name="assembly">Assembly to register</param> public void RegisterAssemblyByConvention(Assembly assembly) { RegisterAssemblyByConvention(assembly, new ConventionalRegistrationConfig()); } /// <summary> /// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method. /// </summary> /// <param name="assembly">Assembly to register</param> /// <param name="config">Additional configuration</param> public void RegisterAssemblyByConvention(Assembly assembly, ConventionalRegistrationConfig config) { var context = new ConventionalRegistrationContext(assembly, this, config); foreach (var registerer in _conventionalRegistrars) { registerer.RegisterAssembly(context); } if (config.InstallInstallers) { IocContainer.Install(FromAssembly.Instance(assembly)); } } /// <summary> /// Registers a type as self registration. /// </summary> /// <typeparam name="TType">Type of the class</typeparam> /// <param name="lifeStyle">Lifestyle of the objects of this type</param> public void Register<TType>(DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton) where TType : class { IocContainer.Register(ApplyLifestyle(Component.For<TType>(), lifeStyle)); } /// <summary> /// Registers a type as self registration. /// </summary> /// <param name="type">Type of the class</param> /// <param name="lifeStyle">Lifestyle of the objects of this type</param> public void Register(Type type, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton) { IocContainer.Register(ApplyLifestyle(Component.For(type), lifeStyle)); } /// <summary> /// Registers a type with it's implementation. /// </summary> /// <typeparam name="TType">Registering type</typeparam> /// <typeparam name="TImpl">The type that implements <see cref="TType"/></typeparam> /// <param name="lifeStyle">Lifestyle of the objects of this type</param> public void Register<TType, TImpl>(DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton) where TType : class where TImpl : class, TType { IocContainer.Register(ApplyLifestyle(Component.For<TType, TImpl>().ImplementedBy<TImpl>(), lifeStyle)); } /// <summary> /// Registers a type with it's implementation. /// </summary> /// <param name="type">Type of the class</param> /// <param name="impl">The type that implements <paramref name="type"/></param> /// <param name="lifeStyle">Lifestyle of the objects of this type</param> public void Register(Type type, Type impl, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton) { IocContainer.Register(ApplyLifestyle(Component.For(type, impl).ImplementedBy(impl), lifeStyle)); } /// <summary> /// Checks whether given type is registered before. /// </summary> /// <param name="type">Type to check</param> public bool IsRegistered(Type type) { return IocContainer.Kernel.HasComponent(type); } /// <summary> /// Checks whether given type is registered before. /// </summary> /// <typeparam name="TType">Type to check</typeparam> public bool IsRegistered<TType>() { return IocContainer.Kernel.HasComponent(typeof(TType)); } /// <summary> /// Gets an object from IOC container. /// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage. /// </summary> /// <typeparam name="T">Type of the object to get</typeparam> /// <returns>The instance object</returns> public T Resolve<T>() { return IocContainer.Resolve<T>(); } /// <summary> /// Gets an object from IOC container. /// Returning object must be Released (see <see cref="Release"/>) after usage. /// </summary> /// <typeparam name="T">Type of the object to cast</typeparam> /// <param name="type">Type of the object to resolve</param> /// <returns>The object instance</returns> public T Resolve<T>(Type type) { return (T)IocContainer.Resolve(type); } /// <summary> /// Gets an object from IOC container. /// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage. /// </summary> /// <typeparam name="T">Type of the object to get</typeparam> /// <param name="argumentsAsAnonymousType">Constructor arguments</param> /// <returns>The instance object</returns> public T Resolve<T>(object argumentsAsAnonymousType) { return IocContainer.Resolve<T>(Arguments.FromProperties(argumentsAsAnonymousType)); } /// <summary> /// Gets an object from IOC container. /// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage. /// </summary> /// <param name="type">Type of the object to get</param> /// <returns>The instance object</returns> public object Resolve(Type type) { return IocContainer.Resolve(type); } /// <summary> /// Gets an object from IOC container. /// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage. /// </summary> /// <param name="type">Type of the object to get</param> /// <param name="argumentsAsAnonymousType">Constructor arguments</param> /// <returns>The instance object</returns> public object Resolve(Type type, object argumentsAsAnonymousType) { return IocContainer.Resolve(type, Arguments.FromProperties(argumentsAsAnonymousType)); } ///<inheritdoc/> public T[] ResolveAll<T>() { return IocContainer.ResolveAll<T>(); } ///<inheritdoc/> public T[] ResolveAll<T>(object argumentsAsAnonymousType) { return IocContainer.ResolveAll<T>(Arguments.FromProperties(argumentsAsAnonymousType)); } ///<inheritdoc/> public object[] ResolveAll(Type type) { return IocContainer.ResolveAll(type).Cast<object>().ToArray(); } ///<inheritdoc/> public object[] ResolveAll(Type type, object argumentsAsAnonymousType) { return IocContainer.ResolveAll(type, Arguments.FromProperties(argumentsAsAnonymousType)).Cast<object>().ToArray(); } /// <summary> /// Releases a pre-resolved object. See Resolve methods. /// </summary> /// <param name="obj">Object to be released</param> public void Release(object obj) { IocContainer.Release(obj); } /// <inheritdoc/> public void Dispose() { IocContainer.Dispose(); } private static ComponentRegistration<T> ApplyLifestyle<T>(ComponentRegistration<T> registration, DependencyLifeStyle lifeStyle) where T : class { switch (lifeStyle) { case DependencyLifeStyle.Transient: return registration.LifestyleTransient(); case DependencyLifeStyle.Singleton: return registration.LifestyleSingleton(); default: return registration; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataLake; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ComputePolicyOperations operations. /// </summary> internal partial class ComputePolicyOperations : IServiceOperations<DataLakeAnalyticsAccountManagementClient>, IComputePolicyOperations { /// <summary> /// Initializes a new instance of the ComputePolicyOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ComputePolicyOperations(DataLakeAnalyticsAccountManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DataLakeAnalyticsAccountManagementClient /// </summary> public DataLakeAnalyticsAccountManagementClient Client { get; private set; } /// <summary> /// Creates or updates the specified compute policy. During update, the compute /// policy with the specified name will be replaced with this new compute /// policy. An account supports, at most, 50 policies /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to add or replace the compute /// policy. /// </param> /// <param name='computePolicyName'> /// The name of the compute policy to create or update. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update the compute policy. The max degree /// of parallelism per job property, min priority per job property, or both /// must be present. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ComputePolicy>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string computePolicyName, ComputePolicyCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (computePolicyName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "computePolicyName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("computePolicyName", computePolicyName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{computePolicyName}", System.Uri.EscapeDataString(computePolicyName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ComputePolicy>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ComputePolicy>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates the specified compute policy. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to which to update the compute /// policy. /// </param> /// <param name='computePolicyName'> /// The name of the compute policy to update. /// </param> /// <param name='parameters'> /// Parameters supplied to update the compute policy. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ComputePolicy>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string computePolicyName, ComputePolicy parameters = default(ComputePolicy), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (computePolicyName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "computePolicyName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("computePolicyName", computePolicyName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{computePolicyName}", System.Uri.EscapeDataString(computePolicyName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ComputePolicy>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ComputePolicy>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified compute policy from the specified Data Lake Analytics /// account /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to delete the /// compute policy. /// </param> /// <param name='computePolicyName'> /// The name of the compute policy to delete. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string computePolicyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (computePolicyName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "computePolicyName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("computePolicyName", computePolicyName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{computePolicyName}", System.Uri.EscapeDataString(computePolicyName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the specified Data Lake Analytics compute policy. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to get the compute /// policy. /// </param> /// <param name='computePolicyName'> /// The name of the compute policy to retrieve. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ComputePolicy>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string computePolicyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (computePolicyName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "computePolicyName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("computePolicyName", computePolicyName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{computePolicyName}", System.Uri.EscapeDataString(computePolicyName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ComputePolicy>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ComputePolicy>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the Data Lake Analytics compute policies within the specified Data /// Lake Analytics account. An account supports, at most, 50 policies /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to get the compute /// policies. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ComputePolicy>>> ListByAccountWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAccount", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ComputePolicy>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ComputePolicy>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the Data Lake Analytics compute policies within the specified Data /// Lake Analytics account. An account supports, at most, 50 policies /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ComputePolicy>>> ListByAccountNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAccountNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ComputePolicy>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ComputePolicy>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using CURLAUTH = Interop.libcurl.CURLAUTH; using CURLcode = Interop.libcurl.CURLcode; using CurlFeatures = Interop.libcurl.CURL_VERSION_Features; using CURLMcode = Interop.libcurl.CURLMcode; using CURLoption = Interop.libcurl.CURLoption; using CurlVersionInfoData = Interop.libcurl.curl_version_info_data; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { #region Constants private const string VerboseDebuggingConditional = "CURLHANDLER_VERBOSE"; private const string HttpPrefix = "HTTP/"; private const char SpaceChar = ' '; private const int StatusCodeLength = 3; private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private const int RequestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private const string NoContentType = HttpKnownHeaderNames.ContentType + ":"; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private readonly static char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF }; private readonly static string[] s_authenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes private readonly static ulong[] s_authSchemePriorityOrder = { CURLAUTH.Negotiate, CURLAUTH.Digest, CURLAUTH.Basic }; private readonly static CurlVersionInfoData s_curlVersionInfoData; private readonly static bool s_supportsAutomaticDecompression; private readonly static bool s_supportsSSL; private readonly MultiAgent _agent = new MultiAgent(); private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private CredentialCache _credentialCache = null; // protected by LockObject private CookieContainer _cookieContainer = new CookieContainer(); private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private object LockObject { get { return _agent; } } #endregion static CurlHandler() { // curl_global_init call handled by Interop.libcurl's cctor // Verify the version of curl we're using is new enough s_curlVersionInfoData = Marshal.PtrToStructure<CurlVersionInfoData>(Interop.libcurl.curl_version_info(CurlAge)); if (s_curlVersionInfoData.age < MinCurlAge) { throw new InvalidOperationException(SR.net_http_unix_https_libcurl_too_old); } // Feature detection s_supportsSSL = (CurlFeatures.CURL_VERSION_SSL & s_curlVersionInfoData.features) != 0; s_supportsAutomaticDecompression = (CurlFeatures.CURL_VERSION_LIBZ & s_curlVersionInfoData.features) != 0; } #region Properties internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy { get { return true; } } internal bool UseProxy { get { return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy; } set { CheckDisposedOrStarted(); _proxyPolicy = value ? ProxyUsePolicy.UseCustomProxy : ProxyUsePolicy.DoNotUseProxy; } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return ClientCertificateOption.Manual; } set { if (ClientCertificateOption.Manual != value) { throw new PlatformNotSupportedException(SR.net_http_unix_invalid_client_cert_option); } } } internal bool SupportsAutomaticDecompression { get { return s_supportsAutomaticDecompression; } } internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value && _credentialCache == null) { _credentialCache = new CredentialCache(); } } } internal bool UseCookie { get { return _useCookie; } set { CheckDisposedOrStarted(); _useCookie = value; } } internal CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( "value", value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } #endregion protected override void Dispose(bool disposing) { _disposed = true; base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException("request", SR.net_http_handler_norequest); } if ((request.RequestUri.Scheme != UriSchemeHttp) && (request.RequestUri.Scheme != UriSchemeHttps)) { throw NotImplemented.ByDesignWithMessage(SR.net_http_client_http_baseaddress_required); } if (request.RequestUri.Scheme == UriSchemeHttps && !s_supportsSSL) { throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } if (_useCookie && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } // TODO: Check that SendAsync is not being called again for same request object. // Probably fix is needed in WinHttpHandler as well CheckDisposed(); SetOperationStarted(); // Do an initial cancellation check to avoid initiating the async operation if // cancellation has already been requested. After this, we'll rely on CancellationToken.Register // to notify us of cancellation requests and shut down the operation if possible. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create the easy request. This associates the easy request with this handler and configures // it based on the settings configured for the handler. var easy = new EasyRequest(this, request, cancellationToken); // Submit the easy request to the multi agent. if (request.Content != null) { // If there is request content to be sent, preload the stream // and submit the request to the multi agent. This is separated // out into a separate async method to avoid associated overheads // in the case where there is no request content stream. return QueueOperationWithRequestContentAsync(easy); } else { // Otherwise, just submit the request. ConfigureAndQueue(easy); return easy.Task; } } private void ConfigureAndQueue(EasyRequest easy) { try { easy.InitializeCurl(); _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New }); } catch (Exception exc) { easy.FailRequest(exc); easy.Cleanup(); // no active processing remains, so we can cleanup } } /// <summary> /// Loads the request's request content stream asynchronously and /// then submits the request to the multi agent. /// </summary> private async Task<HttpResponseMessage> QueueOperationWithRequestContentAsync(EasyRequest easy) { Debug.Assert(easy._requestMessage.Content != null, "Expected request to have non-null request content"); easy._requestContentStream = await easy._requestMessage.Content.ReadAsStreamAsync().ConfigureAwait(false); if (easy._cancellationToken.IsCancellationRequested) { easy.FailRequest(new OperationCanceledException(easy._cancellationToken)); easy.Cleanup(); // no active processing remains, so we can cleanup } else { ConfigureAndQueue(easy); } return await easy.Task.ConfigureAwait(false); } #region Private methods private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private NetworkCredential GetNetworkCredentials(ICredentials credentials, Uri requestUri) { if (_preAuthenticate) { NetworkCredential nc = null; lock (LockObject) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); nc = GetCredentials(_credentialCache, requestUri); } if (nc != null) { return nc; } } return GetCredentials(credentials, requestUri); } private void AddCredentialToCache(Uri serverUri, ulong authAvail, NetworkCredential nc) { lock (LockObject) { for (int i=0; i < s_authSchemePriorityOrder.Length; i++) { if ((authAvail & s_authSchemePriorityOrder[i]) != 0) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); _credentialCache.Add(serverUri, s_authenticationSchemes[i], nc); } } } } private void AddResponseCookies(Uri serverUri, HttpResponseMessage response) { if (!_useCookie) { return; } if (response.Headers.Contains(HttpKnownHeaderNames.SetCookie)) { IEnumerable<string> cookieHeaders = response.Headers.GetValues(HttpKnownHeaderNames.SetCookie); foreach (var cookieHeader in cookieHeaders) { try { _cookieContainer.SetCookies(serverUri, cookieHeader); } catch (CookieException e) { string msg = string.Format("Malformed cookie: SetCookies Failed with {0}, server: {1}, cookie:{2}", e.Message, serverUri.OriginalString, cookieHeader); VerboseTrace(msg); } } } } private static NetworkCredential GetCredentials(ICredentials credentials, Uri requestUri) { if (credentials == null) { return null; } foreach (var authScheme in s_authenticationSchemes) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, authScheme); if (networkCredential != null) { return networkCredential; } } return null; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static void ThrowIfCURLEError(int error) { if (error != CURLcode.CURLE_OK) { var inner = new CurlException(error, isMulti: false); VerboseTrace(inner.Message); throw CreateHttpRequestException(inner); } } private static void ThrowIfCURLMError(int error) { if (error != CURLMcode.CURLM_OK) { string msg = CurlException.GetCurlErrorString(error, true); VerboseTrace(msg); switch (error) { case CURLMcode.CURLM_ADDED_ALREADY: case CURLMcode.CURLM_BAD_EASY_HANDLE: case CURLMcode.CURLM_BAD_HANDLE: case CURLMcode.CURLM_BAD_SOCKET: throw new ArgumentException(msg); case CURLMcode.CURLM_UNKNOWN_OPTION: throw new ArgumentOutOfRangeException(msg); case CURLMcode.CURLM_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLMcode.CURLM_INTERNAL_ERROR: default: throw CreateHttpRequestException(new CurlException(error, msg)); } } } [Conditional(VerboseDebuggingConditional)] private static void VerboseTrace(string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null, MultiAgent agent = null) { // If we weren't handed a multi agent, see if we can get one from the EasyRequest if (agent == null && easy != null && easy._associatedMultiAgent != null) { agent = easy._associatedMultiAgent; } int? agentId = agent != null ? agent.RunningWorkerId : null; // Get an ID string that provides info about which MultiAgent worker and which EasyRequest this trace is about string ids = ""; if (agentId != null || easy != null) { ids = "(" + (agentId != null ? "M#" + agentId : "") + (agentId != null && easy != null ? ", " : "") + (easy != null ? "E#" + easy.Task.Id : "") + ")"; } // Create the message and trace it out string msg = string.Format("[{0, -30}]{1, -16}: {2}", memberName, ids, text); Interop.libc.printf("%s\n", msg); } [Conditional(VerboseDebuggingConditional)] private static void VerboseTraceIf(bool condition, string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null) { if (condition) { VerboseTrace(text, memberName, easy, agent: null); } } private static Exception CreateHttpRequestException(Exception inner = null) { return new HttpRequestException(SR.net_http_client_execution_error, inner); } private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state) { if (!responseHeader.StartsWith(HttpPrefix, StringComparison.OrdinalIgnoreCase)) { return false; } // Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection). response.Headers.Clear(); response.Content.Headers.Clear(); int responseHeaderLength = responseHeader.Length; // Check if line begins with HTTP/1.1 or HTTP/1.0 int prefixLength = HttpPrefix.Length; int versionIndex = prefixLength + 2; if ((versionIndex < responseHeaderLength) && (responseHeader[prefixLength] == '1') && (responseHeader[prefixLength + 1] == '.')) { response.Version = responseHeader[versionIndex] == '1' ? HttpVersion.Version11 : responseHeader[versionIndex] == '0' ? HttpVersion.Version10 : new Version(0, 0); } else { response.Version = new Version(0, 0); } // TODO: Parsing errors are treated as fatal. Find right behaviour int spaceIndex = responseHeader.IndexOf(SpaceChar); if (spaceIndex > -1) { int codeStartIndex = spaceIndex + 1; int statusCode = 0; // Parse first 3 characters after a space as status code if (TryParseStatusCode(responseHeader, codeStartIndex, out statusCode)) { response.StatusCode = (HttpStatusCode)statusCode; int codeEndIndex = codeStartIndex + StatusCodeLength; int reasonPhraseIndex = codeEndIndex + 1; if (reasonPhraseIndex < responseHeaderLength && responseHeader[codeEndIndex] == SpaceChar) { int newLineCharIndex = responseHeader.IndexOfAny(s_newLineCharArray, reasonPhraseIndex); int reasonPhraseEnd = newLineCharIndex >= 0 ? newLineCharIndex : responseHeaderLength; response.ReasonPhrase = responseHeader.Substring(reasonPhraseIndex, reasonPhraseEnd - reasonPhraseIndex); } state._isRedirect = state._handler.AutomaticRedirection && (response.StatusCode == HttpStatusCode.Redirect || response.StatusCode == HttpStatusCode.RedirectKeepVerb || response.StatusCode == HttpStatusCode.RedirectMethod) ; } } return true; } private static bool TryParseStatusCode(string responseHeader, int statusCodeStartIndex, out int statusCode) { if (statusCodeStartIndex + StatusCodeLength > responseHeader.Length) { statusCode = 0; return false; } char c100 = responseHeader[statusCodeStartIndex]; char c10 = responseHeader[statusCodeStartIndex + 1]; char c1 = responseHeader[statusCodeStartIndex + 2]; if (c100 < '0' || c100 > '9' || c10 < '0' || c10 > '9' || c1 < '0' || c1 > '9') { statusCode = 0; return false; } statusCode = (c100 - '0') * 100 + (c10 - '0') * 10 + (c1 - '0'); return true; } private static void HandleRedirectLocationHeader(EasyRequest state, string locationValue) { Debug.Assert(state._isRedirect); Debug.Assert(state._handler.AutomaticRedirection); string location = locationValue.Trim(); //only for absolute redirects Uri forwardUri; if (Uri.TryCreate(location, UriKind.RelativeOrAbsolute, out forwardUri) && forwardUri.IsAbsoluteUri) { NetworkCredential newCredential = GetCredentials(state._handler.Credentials as CredentialCache, forwardUri); state.SetCredentialsOptions(newCredential); // reset proxy - it is possible that the proxy has different credentials for the new URI state.SetProxyOptions(forwardUri); if (state._handler._useCookie) { // reset cookies. state.SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero); // set cookies again state.SetCookieOption(forwardUri); } } } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null, "request is null"); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Tranfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } else if (!chunkedMode) { // Make sure Transfer-Encoding: chunked header is set, // as we have content to send but no known length for it. request.Headers.TransferEncodingChunked = true; } } #endregion private enum ProxyUsePolicy { DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment. UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any. UseCustomProxy = 2 // Use The proxy specified by the user. } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.IO; using System.Xml; using System.Configuration; using System.Windows.Forms; using System.Collections; using System.Text; using WebsitePanel.Setup.Actions; namespace WebsitePanel.Setup { public class EnterpriseServer : BaseSetup { public static object Install(object obj) { return InstallBase(obj, "1.0.1"); } internal static object InstallBase(object obj, string minimalInstallerVersion) { var args = Utils.GetSetupParameters(obj); //check CS version var shellVersion = Utils.GetStringSetupParameter(args, "ShellVersion"); var shellMode = Utils.GetStringSetupParameter(args, Global.Parameters.ShellMode); var version = new Version(shellVersion); var setupVariables = new SetupVariables { ConnectionString = Global.EntServer.AspNetConnectionStringFormat, DatabaseServer = Global.EntServer.DefaultDbServer, Database = Global.EntServer.DefaultDatabase, CreateDatabase = true, WebSiteIP = Global.EntServer.DefaultIP, WebSitePort = Global.EntServer.DefaultPort, WebSiteDomain = String.Empty, NewWebSite = true, NewVirtualDirectory = false, ConfigurationFile = "web.config", UpdateServerAdminPassword = true, ServerAdminPassword = "", }; // InitInstall(args, setupVariables); // var eam = new EntServerActionManager(setupVariables); // eam.PrepareDistributiveDefaults(); // if (shellMode.Equals(Global.SilentInstallerShell, StringComparison.OrdinalIgnoreCase)) { if (version < new Version(minimalInstallerVersion)) { Utils.ShowConsoleErrorMessage(Global.Messages.InstallerVersionIsObsolete, minimalInstallerVersion); // return false; } try { var success = true; // setupVariables.ServerAdminPassword = Utils.GetStringSetupParameter(args, Global.Parameters.ServerAdminPassword); setupVariables.Database = Utils.GetStringSetupParameter(args, Global.Parameters.DatabaseName); setupVariables.DatabaseServer = Utils.GetStringSetupParameter(args, Global.Parameters.DatabaseServer); // setupVariables.DbInstallConnectionString = SqlUtils.BuildDbServerMasterConnectionString( setupVariables.DatabaseServer, Utils.GetStringSetupParameter(args, Global.Parameters.DbServerAdmin), Utils.GetStringSetupParameter(args, Global.Parameters.DbServerAdminPassword) ); // eam.ActionError += new EventHandler<ActionErrorEventArgs>((object sender, ActionErrorEventArgs e) => { Utils.ShowConsoleErrorMessage(e.ErrorMessage); // Log.WriteError(e.ErrorMessage); // success = false; }); // eam.Start(); // return success; } catch (Exception ex) { Log.WriteError("Failed to install the component", ex); // return false; } } else { if (version < new Version(minimalInstallerVersion)) { MessageBox.Show(string.Format(Global.Messages.InstallerVersionIsObsolete, minimalInstallerVersion), "Setup Wizard", MessageBoxButtons.OK, MessageBoxIcon.Warning); return DialogResult.Cancel; } InstallerForm form = new InstallerForm(); Wizard wizard = form.Wizard; wizard.SetupVariables = setupVariables; wizard.ActionManager = eam; //Unattended setup LoadSetupVariablesFromSetupXml(wizard.SetupVariables.SetupXml, wizard.SetupVariables); //create wizard pages var introPage = new IntroductionPage(); var licPage = new LicenseAgreementPage(); var page1 = new ConfigurationCheckPage(); // ConfigurationCheck check1 = new ConfigurationCheck(CheckTypes.OperationSystem, "Operating System Requirement") { SetupVariables = setupVariables }; ConfigurationCheck check2 = new ConfigurationCheck(CheckTypes.IISVersion, "IIS Requirement") { SetupVariables = setupVariables }; ConfigurationCheck check3 = new ConfigurationCheck(CheckTypes.ASPNET, "ASP.NET Requirement") { SetupVariables = setupVariables }; // page1.Checks.AddRange(new ConfigurationCheck[] { check1, check2, check3 }); // var page2 = new InstallFolderPage(); var page3 = new WebPage(); var page4 = new UserAccountPage(); var page5 = new DatabasePage(); var passwordPage = new ServerAdminPasswordPage(); // var page6 = new ExpressInstallPage2(); // var page7 = new FinishPage(); wizard.Controls.AddRange(new Control[] { introPage, licPage, page1, page2, page3, page4, page5, passwordPage, page6, page7 }); wizard.LinkPages(); wizard.SelectedPage = introPage; //show wizard IWin32Window owner = args[Global.Parameters.ParentForm] as IWin32Window; return form.ShowModal(owner); } } public static DialogResult Uninstall(object obj) { return UninstallBase(obj); } public static DialogResult Setup(object obj) { Hashtable args = Utils.GetSetupParameters(obj); string shellVersion = Utils.GetStringSetupParameter(args, "ShellVersion"); // var setupVariables = new SetupVariables { ComponentId = Utils.GetStringSetupParameter(args, Global.Parameters.ComponentId), ConfigurationFile = "web.config", IISVersion = Global.IISVersion, SetupAction = SetupActions.Setup }; // AppConfig.LoadConfiguration(); InstallerForm form = new InstallerForm(); Wizard wizard = form.Wizard; wizard.SetupVariables = setupVariables; // AppConfig.LoadComponentSettings(wizard.SetupVariables); //IntroductionPage page1 = new IntroductionPage(); WebPage page1 = new WebPage(); ServerAdminPasswordPage page2 = new ServerAdminPasswordPage(); ExpressInstallPage page3 = new ExpressInstallPage(); //create install currentScenario InstallAction action = new InstallAction(ActionTypes.UpdateWebSite); action.Description = "Updating web site..."; page3.Actions.Add(action); action = new InstallAction(ActionTypes.UpdateServerAdminPassword); action.Description = "Updating serveradmin password..."; page3.Actions.Add(action); action = new InstallAction(ActionTypes.UpdateConfig); action.Description = "Updating system configuration..."; page3.Actions.Add(action); FinishPage page4 = new FinishPage(); wizard.Controls.AddRange(new Control[] { page1, page2, page3, page4 }); wizard.LinkPages(); wizard.SelectedPage = page1; //show wizard IWin32Window owner = args[Global.Parameters.ParentForm] as IWin32Window; return form.ShowModal(owner); } public static DialogResult Update(object obj) { Hashtable args = Utils.GetSetupParameters(obj); var setupVariables = new SetupVariables { ComponentId = Utils.GetStringSetupParameter(args, Global.Parameters.ComponentId), SetupAction = SetupActions.Update, IISVersion = Global.IISVersion }; AppConfig.LoadConfiguration(); InstallerForm form = new InstallerForm(); Wizard wizard = form.Wizard; wizard.SetupVariables = setupVariables; // AppConfig.LoadComponentSettings(wizard.SetupVariables); IntroductionPage introPage = new IntroductionPage(); LicenseAgreementPage licPage = new LicenseAgreementPage(); ExpressInstallPage page2 = new ExpressInstallPage(); //create install currentScenario InstallAction action = new InstallAction(ActionTypes.Backup); action.Description = "Backing up..."; page2.Actions.Add(action); action = new InstallAction(ActionTypes.DeleteFiles); action.Description = "Deleting files..."; action.Path = "setup\\delete.txt"; page2.Actions.Add(action); action = new InstallAction(ActionTypes.CopyFiles); action.Description = "Copying files..."; page2.Actions.Add(action); action = new InstallAction(ActionTypes.ExecuteSql); action.Description = "Updating database..."; action.Path = "setup\\update_db.sql"; page2.Actions.Add(action); action = new InstallAction(ActionTypes.UpdateConfig); action.Description = "Updating system configuration..."; page2.Actions.Add(action); FinishPage page3 = new FinishPage(); wizard.Controls.AddRange(new Control[] { introPage, licPage, page2, page3 }); wizard.LinkPages(); wizard.SelectedPage = introPage; //show wizard Form parentForm = args[Global.Parameters.ParentForm] as Form; return form.ShowDialog(parentForm); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Buffers; namespace System.SpanTests { public static partial class MemoryMarshalTests { [Fact] public static void CreateFromPinnedArrayInt() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; Memory<int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 3, 2); pinnedMemory.Validate(93, 94); } [Fact] public static void CreateFromPinnedArrayLong() { long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; Memory<long> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 4, 3); pinnedMemory.Validate(94, 95, 96); } [Fact] public static void CreateFromPinnedArrayString() { string[] a = { "90", "91", "92", "93", "94", "95", "96", "97", "98" }; Memory<string> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 4, 3); pinnedMemory.Validate("94", "95", "96"); } [Fact] public static void CreateFromPinnedArrayIntSliceRemainsPinned() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; Memory<int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 3, 5); pinnedMemory.Validate(93, 94, 95, 96, 97); Memory<int> slice = pinnedMemory.Slice(0); TestMemory<int> testSlice = Unsafe.As<Memory<int>, TestMemory<int>>(ref slice); Assert.Equal(3 | (1 << 31), testSlice._index); Assert.Equal(5, testSlice._length); slice = pinnedMemory.Slice(0, pinnedMemory.Length); testSlice = Unsafe.As<Memory<int>, TestMemory<int>>(ref slice); Assert.Equal(3 | (1 << 31), testSlice._index); Assert.Equal(5, testSlice._length); slice = pinnedMemory.Slice(1); testSlice = Unsafe.As<Memory<int>, TestMemory<int>>(ref slice); Assert.Equal(4 | (1 << 31), testSlice._index); Assert.Equal(4, testSlice._length); slice = pinnedMemory.Slice(1, 2); testSlice = Unsafe.As<Memory<int>, TestMemory<int>>(ref slice); Assert.Equal(4 | (1 << 31), testSlice._index); Assert.Equal(2, testSlice._length); } [Fact] public static void CreateFromPinnedArrayIntReadOnlyMemorySliceRemainsPinned() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; ReadOnlyMemory<int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 3, 5); pinnedMemory.Validate(93, 94, 95, 96, 97); ReadOnlyMemory<int> slice = pinnedMemory.Slice(0); TestMemory<int> testSlice = Unsafe.As<ReadOnlyMemory<int>, TestMemory<int>>(ref slice); Assert.Equal(3 | (1 << 31), testSlice._index); Assert.Equal(5, testSlice._length); slice = pinnedMemory.Slice(0, pinnedMemory.Length); testSlice = Unsafe.As<ReadOnlyMemory<int>, TestMemory<int>>(ref slice); Assert.Equal(3 | (1 << 31), testSlice._index); Assert.Equal(5, testSlice._length); slice = pinnedMemory.Slice(1); testSlice = Unsafe.As<ReadOnlyMemory<int>, TestMemory<int>>(ref slice); Assert.Equal(4 | (1 << 31), testSlice._index); Assert.Equal(4, testSlice._length); slice = pinnedMemory.Slice(1, 2); testSlice = Unsafe.As<ReadOnlyMemory<int>, TestMemory<int>>(ref slice); Assert.Equal(4 | (1 << 31), testSlice._index); Assert.Equal(2, testSlice._length); } [Fact] public static void CreateFromPinnedArrayWithStartAndLengthRangeExtendsToEndOfArray() { long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; Memory<long> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 4, 5); pinnedMemory.Validate(94, 95, 96, 97, 98); } [Fact] public static void CreateFromPinnedArrayZeroLength() { int[] empty = Array.Empty<int>(); Memory<int> memory = MemoryMarshal.CreateFromPinnedArray(empty, 0, empty.Length); memory.Validate(); } [Fact] public static void CreateFromPinnedArrayNullArray() { Memory<int> memory = MemoryMarshal.CreateFromPinnedArray((int[])null, 0, 0); memory.Validate(); Assert.Equal(default, memory); } [Fact] public static void CreateFromPinnedArrayNullArrayNonZeroStartAndLength() { Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray((int[])null, 1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray((int[])null, 0, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray((int[])null, 1, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray((int[])null, -1, -1)); } [Fact] public static void CreateFromPinnedArrayWrongArrayType() { // Cannot pass variant array, if array type is not a valuetype. string[] a = { "Hello" }; Assert.Throws<ArrayTypeMismatchException>(() => MemoryMarshal.CreateFromPinnedArray<object>(a, 0, a.Length)); } [Fact] public static void CreateFromPinnedArrayWrongValueType() { // Can pass variant array, if array type is a valuetype. uint[] a = { 42u, 0xffffffffu }; int[] aAsIntArray = (int[])(object)a; Memory<int> memory = MemoryMarshal.CreateFromPinnedArray(aAsIntArray, 0, aAsIntArray.Length); memory.Validate(42, -1); } [Fact] public static void CreateFromPinnedArrayWithNegativeStartAndLength() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, -1, 0)); } [Fact] public static void CreateFromPinnedArrayWithStartTooLargeAndLength() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 4, 0)); } [Fact] public static void CreateFromPinnedArrayWithStartAndNegativeLength() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 0, -1)); } [Fact] public static void CreateFromPinnedArrayWithStartAndLengthTooLarge() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 3, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 2, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 1, 3)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 0, 4)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, int.MaxValue, int.MaxValue)); } [Fact] public static void CreateFromPinnedArrayWithStartAndLengthBothEqual() { // Valid for start to equal the array length. This returns an empty memory that starts "just past the array." int[] a = { 91, 92, 93 }; Memory<int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 3, 0); pinnedMemory.Validate(); } [Fact] public static unsafe void CreateFromPinnedArrayVerifyPinning() { int[] pinnedArray = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; GCHandle pinnedGCHandle = GCHandle.Alloc(pinnedArray, GCHandleType.Pinned); Memory<int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(pinnedArray, 0, 2); void* pinnedPtr = Unsafe.AsPointer(ref MemoryMarshal.GetReference(pinnedMemory.Span)); void* memoryHandlePinnedPtr = pinnedMemory.Pin().Pointer; GC.Collect(); GC.Collect(2); Assert.Equal((int)pinnedPtr, (int)Unsafe.AsPointer(ref MemoryMarshal.GetReference(pinnedMemory.Span))); Assert.Equal((int)memoryHandlePinnedPtr, (int)pinnedGCHandle.AddrOfPinnedObject().ToPointer()); pinnedGCHandle.Free(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace GuildedRose.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace SampleWebApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections; namespace BarcodeLib.Symbologies { /// <summary> /// UPC-A encoding /// Written by: Brad Barnhill /// </summary> class UPCA : BarcodeCommon, IBarcode { private readonly string[] UPC_Code_A = { "0001101", "0011001", "0010011", "0111101", "0100011", "0110001", "0101111", "0111011", "0110111", "0001011" }; private readonly string[] UPC_Code_B = { "1110010", "1100110", "1101100", "1000010", "1011100", "1001110", "1010000", "1000100", "1001000", "1110100" }; private string _countryAssigningManufacturerCode = "N/A"; private readonly Hashtable _countryCodes = new Hashtable(); //is initialized by init_CountryCodes() public UPCA(string input) { Raw_Data = input; } /// <summary> /// Encode the raw data using the UPC-A algorithm. /// </summary> private string Encode_UPCA() { //check length of input if (Raw_Data.Length != 11 && Raw_Data.Length != 12) Error("EUPCA-1: Data length invalid. (Length must be 11 or 12)"); if (!CheckNumericOnly(Raw_Data)) Error("EUPCA-2: Numeric Data Only"); CheckDigit(); var result = "101"; //start with guard bars //first number result += UPC_Code_A[Int32.Parse(Raw_Data[0].ToString())]; //second (group) of numbers var pos = 0; while (pos < 5) { result += UPC_Code_A[Int32.Parse(Raw_Data[pos + 1].ToString())]; pos++; }//while //add divider bars result += "01010"; //third (group) of numbers pos = 0; while (pos < 5) { result += UPC_Code_B[Int32.Parse(Raw_Data[(pos++) + 6].ToString())]; }//while //forth result += UPC_Code_B[Int32.Parse(Raw_Data[Raw_Data.Length - 1].ToString())]; //add ending guard bars result += "101"; //get the manufacturer assigning country init_CountryCodes(); var twodigitCode = "0" + Raw_Data.Substring(0, 1); try { _countryAssigningManufacturerCode = _countryCodes[twodigitCode].ToString(); }//try catch { Error("EUPCA-3: Country assigning manufacturer code not found."); }//catch finally { _countryCodes.Clear(); } return result; }//Encode_UPCA private void init_CountryCodes() { _countryCodes.Clear(); _countryCodes.Add("00", "US / CANADA"); _countryCodes.Add("01", "US / CANADA"); _countryCodes.Add("02", "US / CANADA"); _countryCodes.Add("03", "US / CANADA"); _countryCodes.Add("04", "US / CANADA"); _countryCodes.Add("05", "US / CANADA"); _countryCodes.Add("06", "US / CANADA"); _countryCodes.Add("07", "US / CANADA"); _countryCodes.Add("08", "US / CANADA"); _countryCodes.Add("09", "US / CANADA"); _countryCodes.Add("10", "US / CANADA"); _countryCodes.Add("11", "US / CANADA"); _countryCodes.Add("12", "US / CANADA"); _countryCodes.Add("13", "US / CANADA"); _countryCodes.Add("20", "IN STORE"); _countryCodes.Add("21", "IN STORE"); _countryCodes.Add("22", "IN STORE"); _countryCodes.Add("23", "IN STORE"); _countryCodes.Add("24", "IN STORE"); _countryCodes.Add("25", "IN STORE"); _countryCodes.Add("26", "IN STORE"); _countryCodes.Add("27", "IN STORE"); _countryCodes.Add("28", "IN STORE"); _countryCodes.Add("29", "IN STORE"); _countryCodes.Add("30", "FRANCE"); _countryCodes.Add("31", "FRANCE"); _countryCodes.Add("32", "FRANCE"); _countryCodes.Add("33", "FRANCE"); _countryCodes.Add("34", "FRANCE"); _countryCodes.Add("35", "FRANCE"); _countryCodes.Add("36", "FRANCE"); _countryCodes.Add("37", "FRANCE"); _countryCodes.Add("40", "GERMANY"); _countryCodes.Add("41", "GERMANY"); _countryCodes.Add("42", "GERMANY"); _countryCodes.Add("43", "GERMANY"); _countryCodes.Add("44", "GERMANY"); _countryCodes.Add("45", "JAPAN"); _countryCodes.Add("46", "RUSSIAN FEDERATION"); _countryCodes.Add("49", "JAPAN (JAN-13)"); _countryCodes.Add("50", "UNITED KINGDOM"); _countryCodes.Add("54", "BELGIUM / LUXEMBOURG"); _countryCodes.Add("57", "DENMARK"); _countryCodes.Add("64", "FINLAND"); _countryCodes.Add("70", "NORWAY"); _countryCodes.Add("73", "SWEDEN"); _countryCodes.Add("76", "SWITZERLAND"); _countryCodes.Add("80", "ITALY"); _countryCodes.Add("81", "ITALY"); _countryCodes.Add("82", "ITALY"); _countryCodes.Add("83", "ITALY"); _countryCodes.Add("84", "SPAIN"); _countryCodes.Add("87", "NETHERLANDS"); _countryCodes.Add("90", "AUSTRIA"); _countryCodes.Add("91", "AUSTRIA"); _countryCodes.Add("93", "AUSTRALIA"); _countryCodes.Add("94", "NEW ZEALAND"); _countryCodes.Add("99", "COUPONS"); _countryCodes.Add("471", "TAIWAN"); _countryCodes.Add("474", "ESTONIA"); _countryCodes.Add("475", "LATVIA"); _countryCodes.Add("477", "LITHUANIA"); _countryCodes.Add("479", "SRI LANKA"); _countryCodes.Add("480", "PHILIPPINES"); _countryCodes.Add("482", "UKRAINE"); _countryCodes.Add("484", "MOLDOVA"); _countryCodes.Add("485", "ARMENIA"); _countryCodes.Add("486", "GEORGIA"); _countryCodes.Add("487", "KAZAKHSTAN"); _countryCodes.Add("489", "HONG KONG"); _countryCodes.Add("520", "GREECE"); _countryCodes.Add("528", "LEBANON"); _countryCodes.Add("529", "CYPRUS"); _countryCodes.Add("531", "MACEDONIA"); _countryCodes.Add("535", "MALTA"); _countryCodes.Add("539", "IRELAND"); _countryCodes.Add("560", "PORTUGAL"); _countryCodes.Add("569", "ICELAND"); _countryCodes.Add("590", "POLAND"); _countryCodes.Add("594", "ROMANIA"); _countryCodes.Add("599", "HUNGARY"); _countryCodes.Add("600", "SOUTH AFRICA"); _countryCodes.Add("601", "SOUTH AFRICA"); _countryCodes.Add("609", "MAURITIUS"); _countryCodes.Add("611", "MOROCCO"); _countryCodes.Add("613", "ALGERIA"); _countryCodes.Add("619", "TUNISIA"); _countryCodes.Add("622", "EGYPT"); _countryCodes.Add("625", "JORDAN"); _countryCodes.Add("626", "IRAN"); _countryCodes.Add("690", "CHINA"); _countryCodes.Add("691", "CHINA"); _countryCodes.Add("692", "CHINA"); _countryCodes.Add("729", "ISRAEL"); _countryCodes.Add("740", "GUATEMALA"); _countryCodes.Add("741", "EL SALVADOR"); _countryCodes.Add("742", "HONDURAS"); _countryCodes.Add("743", "NICARAGUA"); _countryCodes.Add("744", "COSTA RICA"); _countryCodes.Add("746", "DOMINICAN REPUBLIC"); _countryCodes.Add("750", "MEXICO"); _countryCodes.Add("759", "VENEZUELA"); _countryCodes.Add("770", "COLOMBIA"); _countryCodes.Add("773", "URUGUAY"); _countryCodes.Add("775", "PERU"); _countryCodes.Add("777", "BOLIVIA"); _countryCodes.Add("779", "ARGENTINA"); _countryCodes.Add("780", "CHILE"); _countryCodes.Add("784", "PARAGUAY"); _countryCodes.Add("785", "PERU"); _countryCodes.Add("786", "ECUADOR"); _countryCodes.Add("789", "BRAZIL"); _countryCodes.Add("850", "CUBA"); _countryCodes.Add("858", "SLOVAKIA"); _countryCodes.Add("859", "CZECH REPUBLIC"); _countryCodes.Add("860", "YUGLOSLAVIA"); _countryCodes.Add("869", "TURKEY"); _countryCodes.Add("880", "SOUTH KOREA"); _countryCodes.Add("885", "THAILAND"); _countryCodes.Add("888", "SINGAPORE"); _countryCodes.Add("890", "INDIA"); _countryCodes.Add("893", "VIETNAM"); _countryCodes.Add("899", "INDONESIA"); _countryCodes.Add("955", "MALAYSIA"); _countryCodes.Add("977", "INTERNATIONAL STANDARD SERIAL NUMBER FOR PERIODICALS (ISSN)"); _countryCodes.Add("978", "INTERNATIONAL STANDARD BOOK NUMBERING (ISBN)"); _countryCodes.Add("979", "INTERNATIONAL STANDARD MUSIC NUMBER (ISMN)"); _countryCodes.Add("980", "REFUND RECEIPTS"); _countryCodes.Add("981", "COMMON CURRENCY COUPONS"); _countryCodes.Add("982", "COMMON CURRENCY COUPONS"); }//init_CountryCodes private void CheckDigit() { try { var rawDataHolder = Raw_Data.Substring(0, 11); //calculate check digit var sum = 0; for (var i = 0; i < rawDataHolder.Length; i++) { if (i % 2 == 0) sum += Int32.Parse(rawDataHolder.Substring(i, 1)) * 3; else sum += Int32.Parse(rawDataHolder.Substring(i, 1)); }//for int cs = (10 - sum % 10) % 10; //replace checksum if provided by the user and replace with the calculated checksum Raw_Data = rawDataHolder + cs; }//try catch { Error("EUPCA-4: Error calculating check digit."); }//catch }//CheckDigit #region IBarcode Members public string Encoded_Value => Encode_UPCA(); #endregion } }
namespace More.ComponentModel { using FluentAssertions; using System; using System.Collections.Generic; using System.ComponentModel; using Xunit; using static System.String; public class ObservableObjectTest { [Fact] public void on_property_changed_should_not_allow_null_argument() { // arrange var observerableObject = new MockObservableObject(); var e = default( PropertyChangedEventArgs ); // act Action onPropertyChanged = () => observerableObject.InvokeOnPropertyChanged( e ); // assert onPropertyChanged.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( e ) ); } [Fact] public void on_property_changed_should_raise_event_for_property() { // arrange var expected = "Test"; var observerableObject = new MockObservableObject(); observerableObject.MonitorEvents(); // act observerableObject.InvokeOnPropertyChanged( expected ); // assert observerableObject.ShouldRaise( nameof( ObservableObject.PropertyChanged ) ) .WithArgs<PropertyChangedEventArgs>( e => e.PropertyName == expected ); } [Fact] public void on_property_changed_should_raise_event_with_argument() { // arrange var expected = new PropertyChangedEventArgs( "Test" ); var observerableObject = new MockObservableObject(); observerableObject.MonitorEvents(); // act observerableObject.InvokeOnPropertyChanged( expected ); // assert observerableObject.ShouldRaise( nameof( ObservableObject.PropertyChanged ) ) .WithArgs<PropertyChangedEventArgs>( e => e == expected ); } [Fact] public void on_property_changed_should_raise_event_for_all_properties() { // arrange var observerableObject = new MockObservableObject(); observerableObject.MonitorEvents(); // act observerableObject.InvokeOnAllPropertiesChanged(); // assert observerableObject.ShouldRaise( nameof( ObservableObject.PropertyChanged ) ) .WithArgs<PropertyChangedEventArgs>( e => IsNullOrEmpty( e.PropertyName ) ); } [Fact] public void on_property_chnaged_should_raise_event_for_property_name() { // arrange var observerableObject = new MockObservableObject(); observerableObject.MonitorEvents(); // act observerableObject.InvokeOnPropertyChanged( nameof( MockObservableObject.IntegerProperty ) ); // assert observerableObject.ShouldRaise( nameof( ObservableObject.PropertyChanged ) ) .WithArgs<PropertyChangedEventArgs>( e => e.PropertyName == nameof( MockObservableObject.IntegerProperty ) ); } [Fact] public void on_property_changing_should_not_allow_null_comparer() { // arrange var observerableObject = new MockObservableObject(); var comparer = default( IEqualityComparer<int> ); // act Action onPropertyChanging = () => observerableObject.InvokeOnPropertyChanging( nameof( MockObservableObject.IntegerProperty ), 0, 1, comparer ); // assert onPropertyChanging.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( comparer ) ); } public static IEnumerable<object[]> SetPropertyNullPropertyNameData { get { var value = 0; yield return new object[] { new Action<MockObservableObject, string>( ( o, pn ) => o.InvokeSetProperty( pn, ref value, 1 ) ), null }; yield return new object[] { new Action<MockObservableObject, string>( ( o, pn ) => o.InvokeSetProperty( pn, ref value, 1 ) ), Empty }; yield return new object[] { new Action<MockObservableObject, string>( ( o, pn ) => o.InvokeSetProperty( pn, ref value, 1, EqualityComparer<int>.Default ) ), null }; yield return new object[] { new Action<MockObservableObject, string>( ( o, pn ) => o.InvokeSetProperty( pn, ref value, 1, EqualityComparer<int>.Default ) ), Empty }; } } [Theory] [MemberData( nameof( SetPropertyNullPropertyNameData ) )] public void set_property_should_allow_null_or_empty_property_name( Action<MockObservableObject, string> invokeSetProperty, string propertyName ) { // arrange var observerableObject = new MockObservableObject(); // act Action setProperty = () => invokeSetProperty( observerableObject, propertyName ); // assert setProperty.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( propertyName ) ); } [Fact] public void set_property_should_not_allow_null_comparer() { // arrange var value = 0; var observerableObject = new MockObservableObject(); var comparer = default( IEqualityComparer<int> ); // act Action setProperty = () => observerableObject.InvokeSetProperty( nameof( MockObservableObject.IntegerProperty ), ref value, 1, comparer ); // assert setProperty.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( comparer ) ); } [Fact] public void set_property_should_change_property() { // arrange var backingField = 0; var observerableObject = new MockObservableObject(); // act observerableObject.InvokeSetProperty( nameof( MockObservableObject.IntegerProperty ), ref backingField, 1 ); // assert backingField.Should().Be( 1 ); } [Fact] public void set_property_should_change_property_with_comparison() { // arrange var backingField = "test"; var expected = "TEST"; var observerableObject = new MockObservableObject(); // act observerableObject.InvokeSetProperty( "StringProperty", ref backingField, "TEST", StringComparer.Ordinal ); // assert backingField.Should().Be( expected ); } public sealed class MockObservableObject : ObservableObject { public int IntegerProperty { get; set; } public string StringProperty { get; set; } public int DoWork() => default( int ); public void InvokeOnPropertyChanged( string propertyName ) => OnPropertyChanged( propertyName ); public void InvokeOnPropertyChanged( PropertyChangedEventArgs e ) => OnPropertyChanged( e ); public void InvokeOnAllPropertiesChanged() => OnAllPropertiesChanged(); public void InvokeOnPropertyChanged<TValue>( string propertyName ) => OnPropertyChanged( propertyName ); public bool InvokeOnPropertyChanging<TValue>( string propertyName, TValue currentValue, TValue newValue ) => OnPropertyChanging( currentValue, newValue, propertyName ); public bool InvokeOnPropertyChanging<TValue>( string propertyName, TValue currentValue, TValue newValue, IEqualityComparer<TValue> comparer ) => OnPropertyChanging( currentValue, newValue, comparer, propertyName ); public void InvokeSetProperty<TValue>( string propertyName, ref TValue currentValue, TValue newValue ) => SetProperty( ref currentValue, newValue, propertyName ); public void InvokeSetProperty<TValue>( string propertyName, ref TValue currentValue, TValue newValue, IEqualityComparer<TValue> comparer ) => SetProperty( ref currentValue, newValue, comparer, propertyName ); } } }
/** * Copyright (c) 2015, GruntTheDivine All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT ,STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. **/ using System; using System.Net; using System.Text; using System.Net.Sockets; using System.Net.Security; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using Iodine.Runtime; namespace Iodine.Modules.Extras { [IodineBuiltinModule ("net/socket")] internal class SocketModule : IodineModule { class IodineProtocolType : IodineObject { private static IodineTypeDefinition SocketProtocalTypeTypeDef = new IodineTypeDefinition ("Socket"); public ProtocolType Type { private set; get; } public IodineProtocolType (ProtocolType protoType) : base (SocketProtocalTypeTypeDef) { this.Type = protoType; } } class IodineSocketType : IodineObject { private static IodineTypeDefinition SocketTypeTypeDef = new IodineTypeDefinition ("Socket"); public SocketType Type { private set; get; } public IodineSocketType (SocketType sockType) : base (SocketTypeTypeDef) { this.Type = sockType; } } class IodineSocketException : IodineException { } public class IodineSocket : IodineObject { private static IodineTypeDefinition SocketTypeDef = new IodineTypeDefinition ("Socket"); public Socket Socket { private set; get; } private System.IO.Stream stream; private static bool ValidateServerCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } public IodineSocket (Socket sock) : base (SocketTypeDef) { Socket = sock; SetAttribute ("connect", new BuiltinMethodCallback (Connect, this)); SetAttribute ("send", new BuiltinMethodCallback (Send, this)); SetAttribute ("bind", new BuiltinMethodCallback (Bind, this)); SetAttribute ("accept", new BuiltinMethodCallback (Accept, this)); SetAttribute ("listen", new BuiltinMethodCallback (Listen, this)); SetAttribute ("receive", new BuiltinMethodCallback (Receive, this)); SetAttribute ("available", new BuiltinMethodCallback (GetBytesAvailable, this)); SetAttribute ("getstream", new BuiltinMethodCallback (GetStream, this)); SetAttribute ("close", new BuiltinMethodCallback (Close, this)); SetAttribute ("connected", new BuiltinMethodCallback (Connected, this)); } public IodineSocket (SocketType sockType, ProtocolType protoType) : this (new Socket (AddressFamily.InterNetwork, sockType, protoType)) { } public override void Exit (VirtualMachine vm) { Socket.Shutdown (SocketShutdown.Both); Socket.Close (); } private IodineObject Connected (VirtualMachine vm, IodineObject self, IodineObject[] args) { try { var result = !((Socket.Poll (1000, SelectMode.SelectRead) && (Socket.Available == 0)) || !Socket.Connected); return IodineBool.Create (result); } catch { return IodineBool.False; } } private IodineObject Close (VirtualMachine vm, IodineObject self, IodineObject[] args) { Socket.Shutdown (SocketShutdown.Both); Socket.Close (); return null; } private IodineObject Bind (VirtualMachine vm, IodineObject self, IodineObject[] args) { if (args.Length < 2) { vm.RaiseException (new IodineArgumentException (2)); return null; } IodineString ipAddrStr = args [0] as IodineString; IodineInteger portObj = args [1] as IodineInteger; if (ipAddrStr == null) { vm.RaiseException (new IodineTypeException ("Str")); return null; } else if (portObj == null) { vm.RaiseException (new IodineTypeException ("Int")); return null; } IPAddress ipAddr; int port = (int)portObj.Value; EndPoint endPoint = null; if (!IPAddress.TryParse (ipAddrStr.ToString (), out ipAddr)) { endPoint = new IPEndPoint (DnsLookUp (ipAddrStr.ToString ()), port); } else { endPoint = new IPEndPoint (ipAddr, port); } try { Socket.Bind (endPoint); } catch { vm.RaiseException ("Could not bind to socket!"); return null; } return null; } private IodineObject Listen (VirtualMachine vm, IodineObject self, IodineObject[] args) { IodineInteger backlogObj = args [0] as IodineInteger; try { int backlog = (int)backlogObj.Value; Socket.Listen (backlog); } catch { vm.RaiseException ("Could not listen to socket!"); return null; } return null; } private IodineSocket Accept (VirtualMachine vm, IodineObject self, IodineObject[] args) { IodineSocket sock = new IodineSocket (Socket.Accept ()); sock.stream = new NetworkStream (sock.Socket); return sock; } private IodineObject Connect (VirtualMachine vm, IodineObject self, IodineObject[] args) { IodineString ipAddrStr = args [0] as IodineString; IodineInteger portObj = args [1] as IodineInteger; IPAddress ipAddr; int port = (int)portObj.Value; EndPoint endPoint = null; if (!IPAddress.TryParse (ipAddrStr.ToString (), out ipAddr)) { endPoint = new IPEndPoint (DnsLookUp (ipAddrStr.ToString ()), port); } else { endPoint = new IPEndPoint (ipAddr, port); } try { Socket.Connect (endPoint); stream = new NetworkStream (this.Socket); } catch (Exception ex) { vm.RaiseException ("Could not connect to socket! (Reason: {0})", ex.Message); return null; } return null; } private IodineObject GetStream (VirtualMachine vm, IodineObject self, IodineObject[] args) { return new IodineStream (stream, true, true); } private IodineObject GetBytesAvailable (VirtualMachine vm, IodineObject self, IodineObject[] args) { return new IodineInteger (Socket.Available); } private IodineObject Send (VirtualMachine vm, IodineObject self, IodineObject[] args) { foreach (IodineObject obj in args) { if (obj is IodineInteger) { stream.WriteByte ((byte)((IodineInteger)obj).Value); stream.Flush (); } else if (obj is IodineString) { var buf = Encoding.UTF8.GetBytes (obj.ToString ()); stream.Write (buf, 0, buf.Length); stream.Flush (); } } return null; } private IodineObject Receive (VirtualMachine vm, IodineObject self, IodineObject[] args) { IodineInteger n = args [0] as IodineInteger; StringBuilder accum = new StringBuilder (); for (int i = 0; i < n.Value; i++) { int b = stream.ReadByte (); if (b != -1) accum.Append ((char)b); } return new IodineString (accum.ToString ()); } private IodineObject ReadLine (VirtualMachine vm, IodineObject self, IodineObject[] args) { StringBuilder accum = new StringBuilder (); int b = stream.ReadByte (); while (b != -1 && b != '\n') { accum.Append ((char)b); b = stream.ReadByte (); } return new IodineString (accum.ToString ()); } /* * I have no idea why, but for some reason using DnsEndPoint for establishing a * socket connection throws a FeatureNotImplemented exception on Mono 4.0.3 so * this will have to do */ private static IPAddress DnsLookUp (string host) { IPHostEntry entries = Dns.GetHostEntry (host); return entries.AddressList [0]; } } public SocketModule () : base ("socket") { SetAttribute ("SOCK_DGRAM", new IodineSocketType (SocketType.Dgram)); SetAttribute ("SOCK_RAW", new IodineSocketType (SocketType.Raw)); SetAttribute ("SOCK_RDM", new IodineSocketType (SocketType.Rdm)); SetAttribute ("SOCK_SEQPACKET", new IodineSocketType (SocketType.Seqpacket)); SetAttribute ("SOCK_STREAM", new IodineSocketType (SocketType.Stream)); SetAttribute ("PROTO_TCP", new IodineProtocolType (ProtocolType.Tcp)); SetAttribute ("PROTO_IP", new IodineProtocolType (ProtocolType.IP)); SetAttribute ("PROTO_IPV4", new IodineProtocolType (ProtocolType.IPv4)); SetAttribute ("PROTO_IPV6", new IodineProtocolType (ProtocolType.IPv6)); SetAttribute ("PROTO_UDP", new IodineProtocolType (ProtocolType.Udp)); SetAttribute ("socket", new BuiltinMethodCallback (socket, this)); } private IodineObject socket (VirtualMachine vm, IodineObject self, IodineObject[] args) { IodineSocketType sockType = args [0] as IodineSocketType; IodineProtocolType protoType = args [1] as IodineProtocolType; return new IodineSocket (sockType.Type, protoType.Type); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Linq; using System.Net; using Microsoft.Rest.Azure; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Test; using Xunit; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Azure.Management.ResourceManager.Models; using System.Collections.Generic; using FluentAssertions; using System.Threading; namespace ResourceGroups.Tests { public class LiveTagsTests : TestBase { const string DefaultLocation = "South Central US"; public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler) { handler.IsPassThrough = true; var client = this.GetResourceManagementClientWithHandler(context, handler); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationRetryTimeout = 0; } return client; } [Fact] public void CreateListAndDeleteSubscriptionTag() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { string tagName = TestUtilities.GenerateName("csmtg"); var client = GetResourceManagementClient(context, handler); var createResult = client.Tags.CreateOrUpdate(tagName); Assert.Equal(tagName, createResult.TagName); var listResult = client.Tags.List(); Assert.True(listResult.Count() > 0); client.Tags.Delete(tagName); } } [Fact] public void CreateListAndDeleteSubscriptionTagValue() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { string tagName = TestUtilities.GenerateName("csmtg"); string tagValue = TestUtilities.GenerateName("csmtgv"); var client = GetResourceManagementClient(context, handler); var createNameResult = client.Tags.CreateOrUpdate(tagName); var createValueResult = client.Tags.CreateOrUpdateValue(tagName, tagValue); Assert.Equal(tagName, createNameResult.TagName); Assert.Equal(tagValue, createValueResult.TagValueProperty); var listResult = client.Tags.List(); Assert.True(listResult.Count() > 0); client.Tags.DeleteValue(tagName, tagValue); client.Tags.Delete(tagName); } } [Fact] public void CreateTagValueWithoutCreatingTag() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { string tagName = TestUtilities.GenerateName("csmtg"); string tagValue = TestUtilities.GenerateName("csmtgv"); var client = GetResourceManagementClient(context, handler); Assert.Throws<CloudException>(() => client.Tags.CreateOrUpdateValue(tagName, tagValue)); } } /// <summary> /// Utility method to test Put request for Tags Operation within tracked resources and proxy resources /// </summary> private void CreateOrUpdateTagsTest(MockContext context, string resourceScope = "") { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var tagsResource = new TagsResource(new Tags( new Dictionary<string, string> { { "tagKey1", "tagValue1" }, { "tagKey2", "tagValue2" } } )); var client = GetResourceManagementClient(context, handler); var subscriptionScope = "/subscriptions/" + client.SubscriptionId; resourceScope = subscriptionScope + resourceScope; // test creating tags for resources var putResponse = client.Tags.CreateOrUpdateAtScope(resourceScope, tagsResource); putResponse.Properties.TagsProperty.Should().HaveCount(tagsResource.Properties.TagsProperty.Count); this.CompareTagsResource(tagsResource, putResponse).Should().BeTrue(); } /// <summary> /// Put request for Tags Operation within tracked resources /// </summary> [Fact] public void CreateTagsWithTrackedResourcesTest() { using (MockContext context = MockContext.Start(this.GetType())) { // test tags for tracked resources string resourceScope = "/resourcegroups/TagsApiSDK/providers/Microsoft.Compute/virtualMachines/TagTestVM"; this.CreateOrUpdateTagsTest(context:context, resourceScope:resourceScope); } } /// <summary> /// Put request for Tags Operation within subscription test /// </summary> [Fact] public void CreateTagsWithSubscriptionTest() { using (MockContext context = MockContext.Start(this.GetType())) { // test tags for subscription this.CreateOrUpdateTagsTest(context: context); } } /// <summary> /// Utility method to test Patch request for Tags Operation within tracked resources and proxy resources, including Replace|Merge|Delete operations /// </summary> private void UpdateTagsTest(MockContext context, string resourceScope = "") { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(context, handler); var subscriptionScope = "/subscriptions/" + client.SubscriptionId; resourceScope = subscriptionScope + resourceScope; // using Tags.CreateOrUpdateAtScope to create two tags initially var tagsResource = new TagsResource(new Tags( new Dictionary<string, string> { { "tagKey1", "tagValue1" }, { "tagKey2", "tagValue2" } } )); client.Tags.CreateOrUpdateAtScope(resourceScope, tagsResource); Thread.Sleep(3000); var putTags = new Tags( new Dictionary<string, string> { { "tagKey1", "tagValue3" }, { "tagKey3", "tagValue3" } }); { // test for Merge operation var tagPatchRequest = new TagsPatchResource("Merge", putTags); var patchResponse = client.Tags.UpdateAtScope(resourceScope, tagPatchRequest); var expectedResponse = new TagsResource(new Tags( new Dictionary<string, string> { { "tagKey1", "tagValue3" }, { "tagKey2", "tagValue2" }, { "tagKey3", "tagValue3" } } )); patchResponse.Properties.TagsProperty.Should().HaveCount(expectedResponse.Properties.TagsProperty.Count); this.CompareTagsResource(expectedResponse, patchResponse).Should().BeTrue(); } { // test for Replace operation var tagPatchRequest = new TagsPatchResource("Replace", putTags); var patchResponse = client.Tags.UpdateAtScope(resourceScope, tagPatchRequest); var expectedResponse = new TagsResource(putTags); patchResponse.Properties.TagsProperty.Should().HaveCount(expectedResponse.Properties.TagsProperty.Count); this.CompareTagsResource(expectedResponse, patchResponse).Should().BeTrue(); } { // test for Delete operation var tagPatchRequest = new TagsPatchResource("Delete", putTags); var patchResponse = client.Tags.UpdateAtScope(resourceScope, tagPatchRequest); patchResponse.Properties.TagsProperty.Should().BeEmpty(); } } /// <summary> /// Patch request for Tags Operation within tracked resources test, including Replace|Merge|Delete operations /// </summary> [Fact] public void UpdateTagsWithTrackedResourcesTest() { using (MockContext context = MockContext.Start(this.GetType())) { // test tags for tracked resources string resourceScope = "/resourcegroups/TagsApiSDK/providers/Microsoft.Compute/virtualMachines/TagTestVM"; this.UpdateTagsTest(context:context, resourceScope: resourceScope); } } /// <summary> /// Patch request for Tags Operation within subscription test, including Replace|Merge|Delete operations /// </summary> [Fact] public void UpdateTagsWithSubscriptionTest() { using (MockContext context = MockContext.Start(this.GetType())) { // test tags for subscription this.UpdateTagsTest(context: context); } } /// <summary> /// Utility method to test Get request for Tags Operation within tracked resources and proxy resources /// </summary> private void GetTagsTest(MockContext context, string resourceScope = "") { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(context, handler); var subscriptionScope = "/subscriptions/" + client.SubscriptionId; resourceScope = subscriptionScope + resourceScope; // using Tags.CreateOrUpdateAtScope to create two tags initially var tagsResource = new TagsResource(new Tags( new Dictionary<string, string> { { "tagKey1", "tagValue1" }, { "tagKey2", "tagValue2" } } )); client.Tags.CreateOrUpdateAtScope(resourceScope, tagsResource); Thread.Sleep(3000); // get request should return created TagsResource var getResponse = client.Tags.GetAtScope(resourceScope); getResponse.Properties.TagsProperty.Should().HaveCount(tagsResource.Properties.TagsProperty.Count); this.CompareTagsResource(tagsResource, getResponse).Should().BeTrue(); } /// <summary> /// Get request for Tags Operation within tracked resources test /// </summary> [Fact] public void GetTagsWithTrackedResourcesTest() { using (MockContext context = MockContext.Start(this.GetType())) { // test tags for tracked resources string resourceScope = "/resourcegroups/TagsApiSDK/providers/Microsoft.Compute/virtualMachines/TagTestVM"; this.GetTagsTest(context: context, resourceScope: resourceScope); } } /// <summary> /// Get request for Tags Operation within subscription test /// </summary> [Fact] public void GetTagsWithSubscriptionTest() { using (MockContext context = MockContext.Start(this.GetType())) { // test tags for subscription this.GetTagsTest(context: context); } } /// <summary> /// Utility method to test Delete request for Tags Operation within tracked resources and proxy resources /// </summary> private TagsResource DeleteTagsTest(MockContext context, string resourceScope = "") { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(context, handler); var subscriptionScope = "/subscriptions/" + client.SubscriptionId; resourceScope = subscriptionScope + resourceScope; // using Tags.CreateOrUpdateAtScope to create two tags initially var tagsResource = new TagsResource(new Tags( new Dictionary<string, string> { { "tagKey1", "tagValue1" }, { "tagKey2", "tagValue2" } } )); client.Tags.CreateOrUpdateAtScope(resourceScope, tagsResource); Thread.Sleep(3000); // try to delete existing tags client.Tags.DeleteAtScope(resourceScope); Thread.Sleep(3000); // after deletion, Get request should get 0 tags back return client.Tags.GetAtScope(resourceScope); } /// <summary> /// Get request for Tags Operation within tracked resources test /// </summary> [Fact] public void DeleteTagsWithTrackedResourcesTest() { using (MockContext context = MockContext.Start(this.GetType())) { // test tags for tracked resources string resourceScope = "/resourcegroups/TagsApiSDK/providers/Microsoft.Compute/virtualMachines/TagTestVM"; this.DeleteTagsTest(context: context, resourceScope: resourceScope).Properties.TagsProperty.Should().BeEmpty(); } } /// <summary> /// Get request for Tags Operation within subscription test /// </summary> [Fact] public void DeleteTagsWithSubscriptionTest() { using (MockContext context = MockContext.Start(this.GetType())) { // test tags for subscription this.DeleteTagsTest(context: context).Properties.TagsProperty.Should().BeNull(); } } /// <summary> /// utility method to compare two TagsResource object to see if they are the same /// </summary> /// <param name="tag1">first TagsResource object</param> /// <param name="tag2">second TagsResource object</param> /// <returns> boolean to show whether two objects are the same</returns> private bool CompareTagsResource(TagsResource tag1, TagsResource tag2) { if ((tag1 == null && tag2 == null) || (tag1.Properties.TagsProperty.Count == 0 && tag2.Properties.TagsProperty.Count == 0)) { return true; } if ((tag1 == null || tag2 == null) || (tag1.Properties.TagsProperty.Count == 0 || tag2.Properties.TagsProperty.Count == 0)) { return false; } foreach (var pair in tag1.Properties.TagsProperty) { if (!tag2.Properties.TagsProperty.ContainsKey(pair.Key) || tag2.Properties.TagsProperty[pair.Key] != pair.Value) { return false; } } return true; } } }
/** * Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; using Ionic.Zip; using Ionic.Zlib; namespace iPhonePackager { /** * Operations performed done at cook time - there should be no calls to the Mac here */ public class CookTime { /// <summary> /// List of files being inserted or updated in the Zip /// </summary> static private HashSet<string> FilesBeingModifiedToPrintOut = new HashSet<string>(); /** * Create and open a work IPA file */ static private ZipFile SetupWorkIPA() { string ReferenceZipPath = Config.GetIPAPathForReading(".stub"); string WorkIPA = Config.GetIPAPath(".ipa"); return CreateWorkingIPA(ReferenceZipPath, WorkIPA); } /// <summary> /// Creates a copy of a source IPA to a working path and opens it up as a Zip for further modifications /// </summary> static private ZipFile CreateWorkingIPA(string SourceIPAPath, string WorkIPAPath) { FileInfo ReferenceInfo = new FileInfo(SourceIPAPath); if (!ReferenceInfo.Exists) { Program.Error(String.Format("Failed to find stub IPA '{0}'", SourceIPAPath)); return null; } else { Program.Log(String.Format("Loaded stub IPA from '{0}' ...", SourceIPAPath)); } if (Program.GameName == "UE4Game") { WorkIPAPath = Config.RemapIPAPath(".ipa"); } // Make sure there are no stale working copies around FileOperations.DeleteFile(WorkIPAPath); // Create a working copy of the IPA FileOperations.CopyRequiredFile(SourceIPAPath, WorkIPAPath); // Open up the zip file ZipFile Stub = ZipFile.Read(WorkIPAPath); // Do a few quick spot checks to catch problems that may have occurred earlier bool bHasCodeSignature = Stub[Config.AppDirectoryInZIP + "/_CodeSignature/CodeResources"] != null; bool bHasMobileProvision = Stub[Config.AppDirectoryInZIP + "/embedded.mobileprovision"] != null; if (!bHasCodeSignature || !bHasMobileProvision) { Program.Error("Stub IPA does not appear to be signed correctly (missing mobileprovision or CodeResources)"); Program.ReturnCode = (int)ErrorCodes.Error_StubNotSignedCorrectly; } // Set encoding to support unicode filenames Stub.AlternateEncodingUsage = ZipOption.Always; Stub.AlternateEncoding = Encoding.UTF8; return Stub; } /// <summary> /// Extracts Info.plist from a Zip /// </summary> static private string ExtractEmbeddedPList(ZipFile Zip) { // Extract the existing Info.plist string PListPathInZIP = String.Format("{0}/Info.plist", Config.AppDirectoryInZIP); if (Zip[PListPathInZIP] == null) { Program.Error("Failed to find Info.plist in IPA (cannot update plist version)"); Program.ReturnCode = (int)ErrorCodes.Error_IPAMissingInfoPList; return ""; } else { // Extract the original into a temporary directory string TemporaryName = Path.GetTempFileName(); FileStream OldFile = File.OpenWrite(TemporaryName); Zip[PListPathInZIP].Extract(OldFile); OldFile.Close(); // Read the text and delete the temporary copy string PListSource = File.ReadAllText(TemporaryName, Encoding.UTF8); File.Delete(TemporaryName); return PListSource; } } static private void CopyEngineOrGameFiles(string Subdirectory, string Filter) { // build the matching paths string EngineDir = Path.Combine(Config.EngineBuildDirectory + Subdirectory); string GameDir = Path.Combine(Config.BuildDirectory + Subdirectory); // find the files in the engine directory string[] EngineFiles = Directory.GetFiles(EngineDir, Filter); if (Directory.Exists(GameDir)) { string[] GameFiles = Directory.GetFiles(GameDir, Filter); // copy all files from game foreach (string GameFilename in GameFiles) { string DestFilename = Path.Combine(Config.PayloadDirectory, Path.GetFileName(GameFilename)); // copy the game verison instead of engine version FileOperations.CopyRequiredFile(GameFilename, DestFilename); } } // look for matching engine files that weren't in game foreach (string EngineFilename in EngineFiles) { string GameFilename = Path.Combine(GameDir, Path.GetFileName(EngineFilename)); string DestFilename = Path.Combine(Config.PayloadDirectory, Path.GetFileName(EngineFilename)); if (!File.Exists(GameFilename)) { // copy the game verison instead of engine version FileOperations.CopyRequiredFile(EngineFilename, DestFilename); } } } static public void CopySignedFiles() { string NameDecoration; if (Program.GameConfiguration == "Development") { NameDecoration = Program.Architecture; } else { NameDecoration = "-IOS-" + Program.GameConfiguration + Program.Architecture; } // Copy and un-decorate the binary name FileOperations.CopyFiles(Config.BinariesDirectory, Config.PayloadDirectory, "<PAYLOADDIR>", Program.GameName + NameDecoration, null); FileOperations.RenameFile(Config.PayloadDirectory, Program.GameName + NameDecoration, Program.GameName); FileOperations.CopyNonEssentialFile( Path.Combine(Config.BinariesDirectory, Program.GameName + NameDecoration + ".app.dSYM.zip"), Path.Combine(Config.PCStagingRootDir, Program.GameName + NameDecoration + ".app.dSYM.zip.datecheck") ); } /** * Callback for setting progress when saving zip file */ static private void UpdateSaveProgress( object Sender, SaveProgressEventArgs Event ) { if (Event.EventType == ZipProgressEventType.Saving_BeforeWriteEntry) { if (FilesBeingModifiedToPrintOut.Contains(Event.CurrentEntry.FileName)) { Program.Log(" ... Packaging '{0}'", Event.CurrentEntry.FileName); } } } /// <summary> /// Updates the version string and then applies the settings in the user overrides plist /// </summary> /// <param name="Info"></param> public static void UpdateVersion(Utilities.PListHelper Info) { // Update the minor version number if the current one is older than the version tracker file // Assuming that the version will be set explicitly in the overrides file for distribution VersionUtilities.UpdateMinorVersion(Info); // Mark the type of build (development or distribution) Info.SetString("EpicPackagingMode", Config.bForDistribution ? "Distribution" : "Development"); } /** * Using the stub IPA previously compiled on the Mac, create a new IPA with assets */ static public void RepackageIPAFromStub() { if (string.IsNullOrEmpty(Config.RepackageStagingDirectory) || !Directory.Exists(Config.RepackageStagingDirectory)) { Program.Error("Directory specified with -stagedir could not be found!"); return; } DateTime StartTime = DateTime.Now; CodeSignatureBuilder CodeSigner = null; // Clean the staging directory Program.ExecuteCommand("Clean", null); // Create a copy of the IPA so as to not trash the original ZipFile Zip = SetupWorkIPA(); if (Zip == null) { return; } string ZipWorkingDir = String.Format("Payload/{0}{1}.app/", Program.GameName, Program.Architecture); FileOperations.ZipFileSystem FileSystem = new FileOperations.ZipFileSystem(Zip, ZipWorkingDir); // Check for a staged plist that needs to be merged into the main one { // Determine if there is a staged one we should try to use instead string PossiblePList = Path.Combine(Config.RepackageStagingDirectory, "Info.plist"); if (File.Exists(PossiblePList)) { if (Config.bPerformResignWhenRepackaging) { Program.Log("Found Info.plist ({0}) in stage, which will be merged in with stub plist contents", PossiblePList); // Merge the two plists, using the staged one as the authority when they conflict byte[] StagePListBytes = File.ReadAllBytes(PossiblePList); string StageInfoString = Encoding.UTF8.GetString(StagePListBytes); byte[] StubPListBytes = FileSystem.ReadAllBytes("Info.plist"); Utilities.PListHelper StubInfo = new Utilities.PListHelper(Encoding.UTF8.GetString(StubPListBytes)); StubInfo.MergePlistIn(StageInfoString); // Write it back to the cloned stub, where it will be used for all subsequent actions byte[] MergedPListBytes = Encoding.UTF8.GetBytes(StubInfo.SaveToString()); FileSystem.WriteAllBytes("Info.plist", MergedPListBytes); } else { Program.Warning("Found Info.plist ({0}) in stage that will be ignored; IPP cannot combine it with the stub plist since -sign was not specified", PossiblePList); } } } // Get the name of the executable file string CFBundleExecutable; { // Load the .plist from the stub byte[] RawInfoPList = FileSystem.ReadAllBytes("Info.plist"); Utilities.PListHelper Info = new Utilities.PListHelper(Encoding.UTF8.GetString(RawInfoPList)); // Get the name of the executable file if (!Info.GetString("CFBundleExecutable", out CFBundleExecutable)) { throw new InvalidDataException("Info.plist must contain the key CFBundleExecutable"); } } // Tell the file system about the executable file name so that we can set correct attributes on // the file when zipping it up FileSystem.ExecutableFileName = CFBundleExecutable; // Prepare for signing if requested if (Config.bPerformResignWhenRepackaging) { // Start the resign process (load the mobileprovision and info.plist, find the cert, etc...) CodeSigner = new CodeSignatureBuilder(); CodeSigner.FileSystem = FileSystem; CodeSigner.PrepareForSigning(); // Merge in any user overrides that exist UpdateVersion(CodeSigner.Info); } // Empty the current staging directory FileOperations.DeleteDirectory(new DirectoryInfo(Config.PCStagingRootDir)); // we will zip files in the pre-staged payload dir string ZipSourceDir = Config.RepackageStagingDirectory; // Save the zip Program.Log("Saving IPA ..."); FilesBeingModifiedToPrintOut.Clear(); Zip.SaveProgress += UpdateSaveProgress; Zip.CompressionLevel = (Ionic.Zlib.CompressionLevel)Config.RecompressionSetting; // Add all of the payload files, replacing existing files in the stub IPA if necessary (should only occur for icons) { string SourceDir = Path.GetFullPath(ZipSourceDir); string[] PayloadFiles = Directory.GetFiles(SourceDir, "*.*", Config.bIterate ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories); foreach (string Filename in PayloadFiles) { // Get the relative path to the file (this implementation only works because we know the files are all // deeper than the base dir, since they were generated from a search) string AbsoluteFilename = Path.GetFullPath(Filename); string RelativeFilename = AbsoluteFilename.Substring(SourceDir.Length + 1).Replace('\\', '/'); string ZipAbsolutePath = String.Format("Payload/{0}{1}.app/{1}", Program.GameName, Program.Architecture, RelativeFilename); byte[] FileContents = File.ReadAllBytes(AbsoluteFilename); if (FileContents.Length == 0) { // Zero-length files added by Ionic cause installation/upgrade to fail on device with error 0xE8000050 // We store a single byte in the files as a workaround for now FileContents = new byte[1]; FileContents[0] = 0; } FileSystem.WriteAllBytes(RelativeFilename, FileContents); if ((FileContents.Length >= 1024 * 1024) || (Config.bVerbose)) { FilesBeingModifiedToPrintOut.Add(ZipAbsolutePath); } } } // Re-sign the executable if there is a signing context if (CodeSigner != null) { if (Config.OverrideBundleName != null) { CodeSigner.Info.SetString("CFBundleDisplayName", Config.OverrideBundleName); string CFBundleIdentifier; if (CodeSigner.Info.GetString("CFBundleIdentifier", out CFBundleIdentifier)) { CodeSigner.Info.SetString("CFBundleIdentifier", CFBundleIdentifier + "_" + Config.OverrideBundleName); } } CodeSigner.PerformSigning(); } // Stick in the iTunesArtwork PNG if available string iTunesArtworkPath = Path.Combine(Config.BuildDirectory, "iTunesArtwork"); if (File.Exists(iTunesArtworkPath)) { Zip.UpdateFile(iTunesArtworkPath, ""); } // Save the Zip Program.Log("Compressing files into IPA (-compress={1}).{0}", Config.bVerbose ? "" : " Only large files will be listed next, but other files are also being packaged.", Config.RecompressionSetting); FileSystem.Close(); TimeSpan ZipLength = DateTime.Now - StartTime; FileInfo FinalZipInfo = new FileInfo(Zip.Name); Program.Log(String.Format("Finished repackaging into {2:0.00} MB IPA, written to '{0}' (took {1:0.00} s for all steps)", Zip.Name, ZipLength.TotalSeconds, FinalZipInfo.Length / (1024.0f * 1024.0f))); } static public bool ExecuteCookCommand(string Command, string RPCCommand) { return false; } } }
using System; using System.Collections.Generic; using System.Data.Services.Client; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime.Versioning; namespace NuGet { public class DataServicePackageRepository : PackageRepositoryBase, IHttpClientEvents, ISearchableRepository, ICloneableRepository, ICultureAwareRepository { private IDataServiceContext _context; private readonly IHttpClient _httpClient; private readonly PackageDownloader _packageDownloader; private CultureInfo _culture; // Just forward calls to the package downloader public event EventHandler<ProgressEventArgs> ProgressAvailable { add { _packageDownloader.ProgressAvailable += value; } remove { _packageDownloader.ProgressAvailable -= value; } } public event EventHandler<WebRequestEventArgs> SendingRequest { add { _packageDownloader.SendingRequest += value; _httpClient.SendingRequest += value; } remove { _packageDownloader.SendingRequest -= value; _httpClient.SendingRequest -= value; } } public PackageDownloader PackageDownloader { get { return _packageDownloader; } } public DataServicePackageRepository(Uri serviceRoot) : this(new HttpClient(serviceRoot)) { } public DataServicePackageRepository(IHttpClient client) : this(client, new PackageDownloader()) { } public DataServicePackageRepository(IHttpClient client, PackageDownloader packageDownloader) { if (client == null) { throw new ArgumentNullException("client"); } if (packageDownloader == null) { throw new ArgumentNullException("packageDownloader"); } _httpClient = client; _httpClient.AcceptCompression = true; _packageDownloader = packageDownloader; } public CultureInfo Culture { get { if (_culture == null) { // TODO: Technically, if this is a remote server, we have to return the culture of the server // instead of invariant culture. However, there is no trivial way to retrieve the server's culture, // So temporarily use Invariant culture here. _culture = _httpClient.Uri.IsLoopback ? CultureInfo.CurrentCulture : CultureInfo.InvariantCulture; } return _culture; } } public override string Source { get { return _httpClient.Uri.OriginalString; } } public override bool SupportsPrereleasePackages { get { return Context.SupportsProperty("IsAbsoluteLatestVersion"); } } // Don't initialize the Context at the constructor time so that // we don't make a web request if we are not going to actually use it // since getting the Uri property of the RedirectedHttpClient will // trigger that functionality. internal IDataServiceContext Context { private get { if (_context == null) { _context = new DataServiceContextWrapper(_httpClient.Uri); _context.SendingRequest += OnSendingRequest; _context.ReadingEntity += OnReadingEntity; _context.IgnoreMissingProperties = true; } return _context; } set { _context = value; } } private void OnReadingEntity(object sender, ReadingWritingEntityEventArgs e) { var package = (DataServicePackage)e.Entity; // REVIEW: This is the only way (I know) to download the package on demand // GetReadStreamUri cannot be evaluated inside of OnReadingEntity. Lazily evaluate it inside DownloadPackage package.Context = Context; package.Downloader = _packageDownloader; } private void OnSendingRequest(object sender, SendingRequestEventArgs e) { // Initialize the request _httpClient.InitializeRequest(e.Request); } public override IQueryable<IPackage> GetPackages() { // REVIEW: Is it ok to assume that the package entity set is called packages? return new SmartDataServiceQuery<DataServicePackage>(Context, Constants.PackageServiceEntitySetName).AsSafeQueryable(); } [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "OData expects a lower case value.")] public IQueryable<IPackage> Search(string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions) { if (!Context.SupportsServiceMethod("Search")) { // If there's no search method then we can't filter by target framework return GetPackages().Find(searchTerm).FilterByPrerelease(allowPrereleaseVersions); } // Convert the list of framework names into short names var shortFrameworkNames = targetFrameworks.Select(name => new FrameworkName(name)) .Select(VersionUtility.GetShortFrameworkName); // Create a '|' separated string of framework names string targetFrameworkString = String.Join("|", shortFrameworkNames); var searchParameters = new Dictionary<string, object> { { "searchTerm", "'" + Escape(searchTerm) + "'" }, { "targetFramework", "'" + Escape(targetFrameworkString) + "'" }, }; if (SupportsPrereleasePackages) { searchParameters.Add("includePrerelease", allowPrereleaseVersions.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); } // Create a query for the search service method var query = Context.CreateQuery<DataServicePackage>("Search", searchParameters); return new SmartDataServiceQuery<DataServicePackage>(Context, query).AsSafeQueryable(); } public IPackageRepository Clone() { return new DataServicePackageRepository(_httpClient, _packageDownloader); } /// <summary> /// Escapes single quotes in the value by replacing them with two single quotes. /// </summary> private static string Escape(string value) { // REVIEW: Couldn't find another way to do this with odata if (!String.IsNullOrEmpty(value)) { return value.Replace("'", "''"); } return value; } } }
// *********************************************************************** // Copyright (c) 2015 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace NUnit.Framework.Internal { /// <summary> /// TestNameGenerator is able to create test names according to /// a coded pattern. /// </summary> public class TestNameGenerator { // TODO: Using a static here is not good it's the easiest // way to get a temporary implementation without passing the // pattern all the way down the test builder hierarchy /// <summary> /// Default pattern used to generate names /// </summary> public static string DefaultTestNamePattern = "{m}{a}"; // The name pattern used by this TestNameGenerator private readonly string _pattern; // The list of NameFragments used to generate names private List<NameFragment> _fragments; /// <summary> /// Construct a TestNameGenerator /// </summary> public TestNameGenerator() { _pattern = DefaultTestNamePattern; } /// <summary> /// Construct a TestNameGenerator /// </summary> /// <param name="pattern">The pattern used by this generator.</param> public TestNameGenerator(string pattern) { _pattern = pattern; } /// <summary> /// Get the display name for a TestMethod and its arguments /// </summary> /// <param name="testMethod">A TestMethod</param> /// <returns>The display name</returns> public string GetDisplayName(TestMethod testMethod) { return GetDisplayName(testMethod, null); } /// <summary> /// Get the display name for a TestMethod and its arguments /// </summary> /// <param name="testMethod">A TestMethod</param> /// <param name="args">Arguments to be used</param> /// <returns>The display name</returns> public string GetDisplayName(TestMethod testMethod, object[] args) { if (_fragments == null) _fragments = BuildFragmentList(_pattern); var result = new StringBuilder(); foreach (var fragment in _fragments) result.Append(fragment.GetText(testMethod, args)); return result.ToString(); } #region Helper Methods private static List<NameFragment> BuildFragmentList(string pattern) { var fragments = new List<NameFragment>(); // Build a list of actions so this generator can be applied to // multiple types and methods. int start = 0; while (start < pattern.Length) { int lcurly = pattern.IndexOf('{', start); if (lcurly < 0) // No more substitutions in pattern break; int rcurly = pattern.IndexOf('}', lcurly); if (rcurly < 0) break; if (lcurly > start) // Handle fixed text before curly brace fragments.Add(new FixedTextFragment(pattern.Substring(start, lcurly - start))); string token = pattern.Substring(lcurly, rcurly - lcurly + 1); switch (token) { case "{m}": fragments.Add(new MethodNameFragment()); break; case "{i}": fragments.Add(new TestIDFragment()); break; case "{n}": fragments.Add(new NamespaceFragment()); break; case "{c}": fragments.Add(new ClassNameFragment()); break; case "{C}": fragments.Add(new ClassFullNameFragment()); break; case "{M}": fragments.Add(new MethodFullNameFragment()); break; case "{a}": fragments.Add(new ArgListFragment(0)); break; case "{0}": case "{1}": case "{2}": case "{3}": case "{4}": case "{5}": case "{6}": case "{7}": case "{8}": case "{9}": int index = token[1] - '0'; fragments.Add(new ArgumentFragment(index, 40)); break; default: char c = token[1]; if (token.Length >= 5 && token[2] == ':' && (c == 'a' || char.IsDigit(c))) { int length; if (int.TryParse(token.Substring(3, token.Length - 4), out length) && length > 0) { if (c == 'a') fragments.Add(new ArgListFragment(length)); else // It's a digit fragments.Add(new ArgumentFragment(c - '0', length)); break; } } // Output the erroneous token to aid user in debugging fragments.Add(new FixedTextFragment(token)); break; } start = rcurly + 1; } // Output any trailing plain text if (start < pattern.Length) fragments.Add(new FixedTextFragment(pattern.Substring(start))); return fragments; } #endregion #region Nested Classes Representing Name Fragments private abstract class NameFragment { private const string THREE_DOTS = "..."; public virtual string GetText(TestMethod testMethod, object[] args) { return GetText(testMethod.Method.MethodInfo, args); } public abstract string GetText(MethodInfo method, object[] args); protected static void AppendGenericTypeNames(StringBuilder sb, MethodInfo method) { sb.Append("<"); int cnt = 0; foreach (Type t in method.GetGenericArguments()) { if (cnt++ > 0) sb.Append(","); sb.Append(t.Name); } sb.Append(">"); } protected static string GetDisplayString(object arg, int stringMax) { string display = arg == null ? "null" : Convert.ToString(arg, System.Globalization.CultureInfo.InvariantCulture); var argArray = arg as Array; if (argArray != null && argArray.Rank == 1) { if (argArray.Length == 0) display = "[]"; else { var builder = new StringBuilder(); builder.Append("["); const int MaxNumItemsToEnumerate = 5; var numItemsToEnumerate = Math.Min(argArray.Length, MaxNumItemsToEnumerate); for (int i = 0; i < numItemsToEnumerate; i++) { if (i > 0) builder.Append(", "); var element = argArray.GetValue(i); var childArray = element as Array; if (childArray != null && childArray.Rank == 1) { builder.Append(childArray.GetType().GetElementType().Name); builder.Append("[]"); } else { var elementDisplayString = GetDisplayString(element, stringMax); builder.Append(elementDisplayString); } } if (argArray.Length > MaxNumItemsToEnumerate) builder.Append(", ..."); builder.Append("]"); display = builder.ToString(); } } else if (arg is double) { double d = (double)arg; if (double.IsNaN(d)) display = "double.NaN"; else if (double.IsPositiveInfinity(d)) display = "double.PositiveInfinity"; else if (double.IsNegativeInfinity(d)) display = "double.NegativeInfinity"; else if (d == double.MaxValue) display = "double.MaxValue"; else if (d == double.MinValue) display = "double.MinValue"; else { if (display.IndexOf('.') == -1) display += ".0"; display += "d"; } } else if (arg is float) { float f = (float)arg; if (float.IsNaN(f)) display = "float.NaN"; else if (float.IsPositiveInfinity(f)) display = "float.PositiveInfinity"; else if (float.IsNegativeInfinity(f)) display = "float.NegativeInfinity"; else if (f == float.MaxValue) display = "float.MaxValue"; else if (f == float.MinValue) display = "float.MinValue"; else { if (display.IndexOf('.') == -1) display += ".0"; display += "f"; } } else if (arg is decimal) { decimal d = (decimal)arg; if (d == decimal.MinValue) display = "decimal.MinValue"; else if (d == decimal.MaxValue) display = "decimal.MaxValue"; else display += "m"; } else if (arg is long) { if (arg.Equals(long.MinValue)) display = "long.MinValue"; else if (arg.Equals(long.MaxValue)) display = "long.MaxValue"; else display += "L"; } else if (arg is ulong) { ulong ul = (ulong)arg; if (ul == ulong.MinValue) display = "ulong.MinValue"; else if (ul == ulong.MaxValue) display = "ulong.MaxValue"; else display += "UL"; } else if (arg is string) { var str = (string)arg; bool tooLong = stringMax > 0 && str.Length > stringMax; int limit = tooLong ? stringMax - THREE_DOTS.Length : 0; var sb = new StringBuilder(); sb.Append("\""); foreach (char c in str) { sb.Append(EscapeCharInString(c)); if (tooLong && sb.Length > limit) { sb.Append(THREE_DOTS); break; } } sb.Append("\""); display = sb.ToString(); } else if (arg is char) { display = "\'" + EscapeSingleChar((char)arg) + "\'"; } else if (arg is int) { if (arg.Equals(int.MaxValue)) display = "int.MaxValue"; else if (arg.Equals(int.MinValue)) display = "int.MinValue"; } else if (arg is uint) { if (arg.Equals(uint.MaxValue)) display = "uint.MaxValue"; else if (arg.Equals(uint.MinValue)) display = "uint.MinValue"; } else if (arg is short) { if (arg.Equals(short.MaxValue)) display = "short.MaxValue"; else if (arg.Equals(short.MinValue)) display = "short.MinValue"; } else if (arg is ushort) { if (arg.Equals(ushort.MaxValue)) display = "ushort.MaxValue"; else if (arg.Equals(ushort.MinValue)) display = "ushort.MinValue"; } else if (arg is byte) { if (arg.Equals(byte.MaxValue)) display = "byte.MaxValue"; else if (arg.Equals(byte.MinValue)) display = "byte.MinValue"; } else if (arg is sbyte) { if (arg.Equals(sbyte.MaxValue)) display = "sbyte.MaxValue"; else if (arg.Equals(sbyte.MinValue)) display = "sbyte.MinValue"; } return display; } private static string EscapeSingleChar(char c) { if (c == '\'') return "\\\'"; return EscapeControlChar(c); } private static string EscapeCharInString(char c) { if (c == '"') return "\\\""; return EscapeControlChar(c); } private static string EscapeControlChar(char c) { switch (c) { case '\\': return "\\\\"; case '\0': return "\\0"; case '\a': return "\\a"; case '\b': return "\\b"; case '\f': return "\\f"; case '\n': return "\\n"; case '\r': return "\\r"; case '\t': return "\\t"; case '\v': return "\\v"; case '\x0085': case '\x2028': case '\x2029': return string.Format("\\x{0:X4}", (int)c); default: return c.ToString(); } } } private class TestIDFragment : NameFragment { public override string GetText(MethodInfo method, object[] args) { return "{i}"; // No id available using MethodInfo } public override string GetText(TestMethod testMethod, object[] args) { return testMethod.Id; } } private class FixedTextFragment : NameFragment { private readonly string _text; public FixedTextFragment(string text) { _text = text; } public override string GetText(MethodInfo method, object[] args) { return _text; } } private class MethodNameFragment : NameFragment { public override string GetText(MethodInfo method, object[] args) { var sb = new StringBuilder(); sb.Append(method.Name); if (method.IsGenericMethod) AppendGenericTypeNames(sb, method); return sb.ToString(); } } private class NamespaceFragment : NameFragment { public override string GetText(MethodInfo method, object[] args) { return method.DeclaringType.Namespace; } } private class MethodFullNameFragment : NameFragment { public override string GetText(MethodInfo method, object[] args) { var sb = new StringBuilder(); sb.Append(method.DeclaringType.FullName); sb.Append('.'); sb.Append(method.Name); if (method.IsGenericMethod) AppendGenericTypeNames(sb, method); return sb.ToString(); } } private class ClassNameFragment : NameFragment { public override string GetText(MethodInfo method, object[] args) { return method.DeclaringType.Name; } } private class ClassFullNameFragment : NameFragment { public override string GetText(MethodInfo method, object[] args) { return method.DeclaringType.FullName; } } private class ArgListFragment : NameFragment { private readonly int _maxStringLength; public ArgListFragment(int maxStringLength) { _maxStringLength = maxStringLength; } public override string GetText(MethodInfo method, object[] arglist) { var sb = new StringBuilder(); if (arglist != null) { sb.Append('('); for (int i = 0; i < arglist.Length; i++) { if (i > 0) sb.Append(","); sb.Append(GetDisplayString(arglist[i], _maxStringLength)); } sb.Append(')'); } return sb.ToString(); } } private class ArgumentFragment : NameFragment { private readonly int _index; private readonly int _maxStringLength; public ArgumentFragment(int index, int maxStringLength) { _index = index; _maxStringLength = maxStringLength; } public override string GetText(MethodInfo method, object[] args) { return _index < args.Length ? GetDisplayString(args[_index], _maxStringLength) : string.Empty; } } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using Android.Runtime; using FFmpeg.AutoGen; using osu.Framework.Extensions.EnumExtensions; using osu.Framework.Graphics.Video; using osu.Framework.Logging; namespace osu.Framework.Android.Graphics.Video { // ReSharper disable InconsistentNaming public unsafe class AndroidVideoDecoder : VideoDecoder { private const string lib_avutil = "libavutil.so"; private const string lib_avcodec = "libavcodec.so"; private const string lib_avformat = "libavformat.so"; private const string lib_swscale = "libswscale.so"; private const string lib_avfilter = "libavfilter.so"; [DllImport(lib_avutil)] private static extern AVFrame* av_frame_alloc(); [DllImport(lib_avutil)] private static extern void av_frame_free(AVFrame** frame); [DllImport(lib_avutil)] private static extern void av_frame_unref(AVFrame* frame); [DllImport(lib_avcodec)] private static extern int av_frame_get_buffer(AVFrame* frame, int align); [DllImport(lib_avutil)] private static extern byte* av_strdup(string s); [DllImport(lib_avutil)] private static extern int av_strerror(int errnum, byte* buffer, ulong bufSize); [DllImport(lib_avutil)] private static extern void* av_malloc(ulong size); [DllImport(lib_avutil)] private static extern void av_freep(void* ptr); [DllImport(lib_avcodec)] private static extern AVPacket* av_packet_alloc(); [DllImport(lib_avcodec)] private static extern void av_packet_unref(AVPacket* pkt); [DllImport(lib_avcodec)] private static extern void av_frame_move_ref(AVFrame* dst, AVFrame* src); [DllImport(lib_avcodec)] private static extern void av_packet_free(AVPacket** pkt); [DllImport(lib_avformat)] private static extern int av_read_frame(AVFormatContext* s, AVPacket* pkt); [DllImport(lib_avformat)] private static extern int av_seek_frame(AVFormatContext* s, int stream_index, long timestamp, int flags); [DllImport(lib_avutil)] private static extern int av_hwdevice_ctx_create(AVBufferRef** device_ctx, AVHWDeviceType type, [MarshalAs(UnmanagedType.LPUTF8Str)] string device, AVDictionary* opts, int flags); [DllImport(lib_avutil)] private static extern int av_hwframe_transfer_data(AVFrame* dst, AVFrame* src, int flags); [DllImport(lib_avcodec)] private static extern AVCodec* av_codec_iterate(void** opaque); [DllImport(lib_avcodec)] private static extern int av_codec_is_decoder(AVCodec* codec); [DllImport(lib_avcodec)] private static extern AVCodecHWConfig* avcodec_get_hw_config(AVCodec* codec, int index); [DllImport(lib_avcodec)] private static extern AVCodecContext* avcodec_alloc_context3(AVCodec* codec); [DllImport(lib_avcodec)] private static extern void avcodec_free_context(AVCodecContext** avctx); [DllImport(lib_avcodec)] private static extern int avcodec_parameters_to_context(AVCodecContext* codec, AVCodecParameters* par); [DllImport(lib_avcodec)] private static extern int avcodec_open2(AVCodecContext* avctx, AVCodec* codec, AVDictionary** options); [DllImport(lib_avcodec)] private static extern int avcodec_receive_frame(AVCodecContext* avctx, AVFrame* frame); [DllImport(lib_avcodec)] private static extern int avcodec_send_packet(AVCodecContext* avctx, AVPacket* avpkt); [DllImport(lib_avcodec)] private static extern void avcodec_flush_buffers(AVCodecContext* avctx); [DllImport(lib_avformat)] private static extern AVFormatContext* avformat_alloc_context(); [DllImport(lib_avformat)] private static extern void avformat_close_input(AVFormatContext** s); [DllImport(lib_avformat)] private static extern int avformat_find_stream_info(AVFormatContext* ic, AVDictionary** options); [DllImport(lib_avformat)] private static extern int avformat_open_input(AVFormatContext** ps, [MarshalAs(UnmanagedType.LPUTF8Str)] string url, AVInputFormat* fmt, AVDictionary** options); [DllImport(lib_avformat)] private static extern int av_find_best_stream(AVFormatContext* ic, AVMediaType type, int wanted_stream_nb, int related_stream, AVCodec** decoder_ret, int flags); [DllImport(lib_avformat)] private static extern AVIOContext* avio_alloc_context(byte* buffer, int buffer_size, int write_flag, void* opaque, avio_alloc_context_read_packet_func read_packet, avio_alloc_context_write_packet_func write_packet, avio_alloc_context_seek_func seek); [DllImport(lib_avformat)] private static extern void avio_context_free(AVIOContext** s); [DllImport(lib_swscale)] private static extern void sws_freeContext(SwsContext* swsContext); [DllImport(lib_swscale)] private static extern SwsContext* sws_getCachedContext(SwsContext* context, int srcW, int srcH, AVPixelFormat srcFormat, int dstW, int dstH, AVPixelFormat dstFormat, int flags, SwsFilter* srcFilter, SwsFilter* dstFilter, double* param); [DllImport(lib_swscale)] private static extern int sws_scale(SwsContext* c, byte*[] srcSlice, int[] srcStride, int srcSliceY, int srcSliceH, byte*[] dst, int[] dstStride); [DllImport(lib_avcodec)] private static extern int av_jni_set_java_vm(void* vm, void* logCtx); public AndroidVideoDecoder(string filename) : base(filename) { } public AndroidVideoDecoder(Stream videoStream) : base(videoStream) { // Hardware decoding with MediaCodec requires that we pass a Java VM pointer // to FFmpeg so that it can call the MediaCodec APIs through JNI (as they're Java only). // Unfortunately, Xamarin doesn't publicly expose this pointer anywhere, so we have to get it through reflection... const string java_vm_field_name = "java_vm"; var jvmPtrInfo = typeof(JNIEnv).GetField(java_vm_field_name, BindingFlags.NonPublic | BindingFlags.Static); object jvmPtrObj = jvmPtrInfo?.GetValue(null); Debug.Assert(jvmPtrObj != null); int result = av_jni_set_java_vm((void*)(IntPtr)jvmPtrObj, null); if (result < 0) throw new InvalidOperationException($"Couldn't pass Java VM handle to FFmpeg: ${result}"); } protected override IEnumerable<(FFmpegCodec codec, AVHWDeviceType hwDeviceType)> GetAvailableDecoders( AVInputFormat* inputFormat, AVCodecID codecId, HardwareVideoDecoder targetHwDecoders ) { if (targetHwDecoders.HasFlagFast(HardwareVideoDecoder.MediaCodec)) { string formatName = Marshal.PtrToStringAnsi((IntPtr)inputFormat->name); switch (formatName) { // MediaCodec doesn't return correct timestamps when playing back AVI files // which results in the video running at ~30% less FPS than it's supposed to. case "avi": { Logger.Log($"Disabling HW decoding for this video because of unsupported input format: ${formatName}"); targetHwDecoders &= ~HardwareVideoDecoder.MediaCodec; break; } } } return base.GetAvailableDecoders(inputFormat, codecId, targetHwDecoders); } protected override FFmpegFuncs CreateFuncs() => new FFmpegFuncs { av_frame_alloc = av_frame_alloc, av_frame_free = av_frame_free, av_frame_unref = av_frame_unref, av_frame_move_ref = av_frame_move_ref, av_frame_get_buffer = av_frame_get_buffer, av_strdup = av_strdup, av_strerror = av_strerror, av_malloc = av_malloc, av_freep = av_freep, av_packet_alloc = av_packet_alloc, av_packet_unref = av_packet_unref, av_packet_free = av_packet_free, av_read_frame = av_read_frame, av_seek_frame = av_seek_frame, av_hwdevice_ctx_create = av_hwdevice_ctx_create, av_hwframe_transfer_data = av_hwframe_transfer_data, av_codec_iterate = av_codec_iterate, av_codec_is_decoder = av_codec_is_decoder, avcodec_get_hw_config = avcodec_get_hw_config, avcodec_alloc_context3 = avcodec_alloc_context3, avcodec_free_context = avcodec_free_context, avcodec_parameters_to_context = avcodec_parameters_to_context, avcodec_open2 = avcodec_open2, avcodec_receive_frame = avcodec_receive_frame, avcodec_send_packet = avcodec_send_packet, avcodec_flush_buffers = avcodec_flush_buffers, avformat_alloc_context = avformat_alloc_context, avformat_close_input = avformat_close_input, avformat_find_stream_info = avformat_find_stream_info, avformat_open_input = avformat_open_input, av_find_best_stream = av_find_best_stream, avio_alloc_context = avio_alloc_context, avio_context_free = avio_context_free, sws_freeContext = sws_freeContext, sws_getCachedContext = sws_getCachedContext, sws_scale = sws_scale }; } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Toolbox { /// <summary> /// A class that can not be instantiated. /// </summary> public class AlwaysNull { private AlwaysNull() { throw new NotImplementedException(); } } public static class Extensions { /// <summary> /// Returns the rightmost characters of a string. /// </summary> /// <param name="string">Source string.</param> /// <param name="count">Number of characters to take.</param> /// <returns>The rightmost characters of a string.</returns> public static string Right(this string source, int count) { if (string.IsNullOrEmpty(source)) { return string.Empty; } int len = source.Length; if (count < 0) { throw new ArgumentException("Count must be a non-negative integer."); } if (count > len) { throw new ArgumentOutOfRangeException(); } return source.Substring(len - count, count); } /// <summary> /// Shorthand to determine whether an object reference is null or not. Safe to call on null objects. /// </summary> /// <param name="source">Object to compare.</param> /// <returns>True if the object references null, false otherwise.</returns> public static bool ReferenceEqualsNull(this object source) { return object.ReferenceEquals(null, source); } /// <summary> /// Filters an enumerable collection and only reutrns items that are not null. /// </summary> /// <param name="source">Collection to filter.</param> /// <returns>The filtered collection.</returns> public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> source) { return source.Where(x => !Object.ReferenceEquals(null, x)); } /// <summary> /// Compares the n'th item of every single list in a collection and returns that value /// if they are all the same, or null. Do not use this method to compare lists of nulls. /// </summary> /// <typeparam name="T">Type of item in the collection of lists.</typeparam> /// <param name="source">Collection of lists to compare.</param> /// <param name="defaultValue">Value to use when the n'th item is not the same or does not exist.</param> /// <returns>A container list. This will have the same number of elements as the /// longest source list. </returns> /// <example> /// <code> /// var m = ("monthber").Select(x => x).ToList(); /// var n = ("November").Select(x => x).ToList(); /// var d = ("December").Select(x => x).ToList(); /// /// var intersect = (new List<List<char>>() { m, n, d }).ListIntersect(" "); /// /// Console.WriteLine(String.Join("", intersect)); /// </code> /// Console output: /// ber /// </example> public static IList<object> ListIntersect<T>(this List<List<T>> source, object defaultValue = null) { // The general outline of this function is to compare the n'th position // of every single list. // Find the shortest list from the inputs int minListLength = source.Min(x => x.Count()); // Find the longest list from the inputs int maxListLength = source.Max(x => x.Count()); // Index while traversing every single list int listIndex = 0; // Number of input lists int length = source.Count(); // Result list List<object> results = new List<object>(); // Look at the n'th item for every list. This only // needs to occur up to the shortest common list. for (; listIndex < minListLength; listIndex++) { // Pull out the n'th item from every list and store it here. List<object> toCompare = new List<object>(); T first = default(T); bool firstSet = false; // Why is toCompare built in a for loop? // Well, there is a very simple select statement to build this: // // var toCompare = source.Select(x => listIndex < x.Count() ? x[listIndex] : null); // // which results in a compile error. This is due to 'null' having an unspecified // type, and/or the compiler being unsure that 'T' can be coerced to a null value. // If this wasn't a generic function the above could be fixed with an explicit cast, // say, to a nullable type. See http://stackoverflow.com/a/18260915/1462295 for (int sourceIndex = 0; sourceIndex < length; sourceIndex++) { var list = source[sourceIndex]; // Pull out the n'th item, or null. if (listIndex < list.Count()) { toCompare.Add(list[listIndex]); if (!firstSet) { firstSet = true; first = list[listIndex]; } } else { toCompare.Add(defaultValue); } } // If there's nothing to compare, just skip to the next position. if (!firstSet) { results.Add(defaultValue); continue; } // Look at every single n'th item. If it's null, or there's something that's different, // they are not all the same. var isDifferent = toCompare.Any(x => Object.ReferenceEquals(null, x) || !x.Equals(first)); if (!isDifferent) { results.Add(first); } else { results.Add(defaultValue); } } // If the list lengths are not the same, fill out the remaining values with null. for (; listIndex < maxListLength; listIndex++) { results.Add(defaultValue); } return results; } /// <summary> /// Iterates a collection with an index. /// </summary> /// <typeparam name="T">Type of collection.</typeparam> /// <param name="source">Collection to enumerate.</param> /// <returns>Enumerable of collection where each item is paired with its index.</returns> public static IEnumerable<Tuple<int, T>> EnumerateWithIndex<T>(this IEnumerable<T> source) { int index = 0; foreach (var item in source) { yield return new Tuple<int, T>(index, item); index++; } } /// <summary> /// Enumerates a collection performing an action on each item. The index of the item is /// also passed as a paramter to the action. /// </summary> /// <typeparam name="T">Type of collection.</typeparam> /// <param name="source">Collection of objects to enumerate.</param> /// <param name="action">Action to perform on each object. Accepts two parameters, the object and the index.</param> /// <remarks>http://stackoverflow.com/a/43035/1462295</remarks> public static void ForEachWithIndex<T>(this IEnumerable<T> source, Action<T, int> action) { int index = 0; foreach (var item in source) { action(item, index); index++; } } /// <summary> /// Method to cast to a different type. /// </summary> /// <typeparam name="T">Type to cast to.</typeparam> /// <param name="source">Object to cast.</param> /// <returns>Objected casted to new type.</returns> public static T As<T>(this object source) where T : class { return source as T; } /// <summary> /// Takes an enumerable set of objects and casts each one to a new type using "as". /// </summary> /// <remarks> /// Used for unboxing; would fail trying to convert doubles to int. /// </remarks> /// <typeparam name="T">Type to cast to.</typeparam> /// <param name="source">Enumerable set of objects to cast.</param> /// <returns>Enumerable set of objects casted to new type.</returns> public static IEnumerable<T> AsList<T>(this IEnumerable<object> source) where T : class { return source.Select(x => x as T); } /// <summary> /// Takes an enumerable set of objects and casts each one to a new type using an explicit cast. /// </summary> /// <remarks> /// This could be used to truncate a list of doubles to ints. /// </remarks> /// <typeparam name="T">Type to cast to.</typeparam> /// <param name="source">Enumerable set of objects to cast.</param> /// <returns>Enumerable set of objects casted to new type.</returns> public static IEnumerable<T> AsListExplicit<T>(this IEnumerable<object> source) { return source.Select(x => (T)x); } /// <summary> /// Takes an enumerable set of objects and calls ToString on each. /// </summary> /// <param name="source">Enumerable set of objects to cast.</param> /// <returns>Enumerable set of objects, each cast ToString.</returns> public static IEnumerable<string> ToStringList(this IEnumerable<object> source) { return source.Select(x => x.ToString()); } /// <summary> /// Takes an enumerable set of objects and calls ToString on each. /// </summary> /// <typeparam name="T">Type to cast from.</typeparam> /// <param name="source">Enumerable set of objects to cast.</param> /// <returns>Enumerable set of objects, each cast ToString.</returns> public static IEnumerable<string> ToStringList<T>(this IEnumerable<T> source) { return source.Select(x => x.ToString()); } /// <summary> /// Takes an enumerable and joins the elements into a string. /// </summary> /// <param name="collection">Enumberable set of objects to join.</param> /// <param name="joiner">String to join elements with.</param> /// <returns>String containing joined elements.</returns> public static string JoinAsString(this IEnumerable<object> collection, string joiner = ",") { return string.Join(joiner, collection); } /// <summary> /// Takes an enumerable and joins the elements into a string. /// </summary> /// <param name="collection">Enumberable set of objects to join.</param> /// <param name="joiner">String to join elements with.</param> /// <returns>String containing joined elements.</returns> public static string JoinAsString<T>(this IEnumerable<T> collection, string joiner = ",") { return string.Join(joiner, collection); } /// <summary> /// Gets a value indicating whether this object is between the start and end objects. /// Comparison is inclusive. /// </summary> /// <param name="start">Start object to compare against. Expected to be same type as T, but not enforced.</param> /// <param name="end">End object to compare against. Expected to be same type as T, but not enforced.</param> /// <returns>Whether this item is between the two given items.</returns> public static bool Between<T>(this T self, object start, object end) where T : IComparable { if (object.ReferenceEquals(null, self)) { return false; } if (object.ReferenceEquals(null, start)) { return false; } if (object.ReferenceEquals(null, end)) { return false; } return self.CompareTo(start) >= 0 && self.CompareTo(end) <= 0; } /// <summary> /// Call JsonConvert to deserialize a string into an object. /// </summary> /// <typeparam name="T">Type of object to deserialize into.</typeparam> /// <param name="s">Source to deserialize.</param> /// <returns>Newly created object.</returns> public static T DeserializeAs<T>(this string s) { return JsonConvert.DeserializeObject<T>(s); } /// <summary> /// Call JsonConvert to deserialize a string into an object, starting at a root node. /// </summary> /// <typeparam name="T">Type of object to deserialize into.</typeparam> /// <param name="s">Source to deserialize.</param> /// <param name="root">Root node to deserialize from.</param> /// <returns>Newly created object.</returns> public static T DeserializeAs<T>(this string s, string root) { JToken parsed = JObject.Parse(s); JToken rootNode = parsed[root]; return JsonConvert.DeserializeObject<T>(rootNode.ToString()); } /// <summary> /// Generic method to cast an object into another object with result status. /// </summary> /// <typeparam name="T">Type of object to cast into.</typeparam> /// <param name="source">Source object to cast.</param> /// <param name="res">Resulting object, if cast was successful.</param> /// <returns>True if the cast results in a non-null object, false otherwise.</returns> public static bool TryAs<T>(this object source, ref T res) where T : class { if (object.ReferenceEquals(null, source)) { return false; } T casted = source as T; if (object.ReferenceEquals(null, casted)) { return false; } res = casted; return true; } /// <summary> /// Cast an object to string, then parse into an int with result status. /// <param name="source">Source object to cast.</param> /// <param name="res">Resulting int, if cast was successful.</param> /// <returns>True if TryParse was successful, false otherwise.</returns> public static bool TryAs(this object source, ref int res) { if (object.ReferenceEquals(null, source)) { return false; } int i = 0; if (int.TryParse(source.ToString(), out i)) { res = i; return true; } return false; } /// <summary> /// Cast an object to string, then parse into an double with result status. /// <param name="source">Source object to cast.</param> /// <param name="res">Resulting double, if cast was successful.</param> /// <returns>True if TryParse was successful, false otherwise.</returns> public static bool TryAs(this object source, ref double res) { if (object.ReferenceEquals(null, source)) { return false; } double d = 0; if (double.TryParse(source.ToString(), out d)) { res = d; return true; } return false; } /// <summary> /// Cast an object to string, then parse into an DateTime with result status. /// <param name="source">Source object to cast.</param> /// <param name="res">Resulting DateTimes, if cast was successful.</param> /// <returns>True if TryParse was successful, false otherwise.</returns> public static bool TryAs(this object source, ref DateTime res) { if (object.ReferenceEquals(null, source)) { return false; } DateTime d = DateTime.MinValue; if (DateTime.TryParse(source.ToString(), out d)) { res = d; return true; } return false; } /// <summary> /// Creates an enumerable containing the object. /// </summary> /// <typeparam name="T">Type of object and enumerable.</typeparam> /// <param name="item">Object to contain in the enumerable.</param> /// <returns>Enumerable of the object.</returns> public static IEnumerable<T> Enumerify<T>(T item) { var results = Enumerable.Empty<T>(); results = results.Concat(new T[] { item }); return results; } /// <summary> /// Creates an enumerable containing the objects. /// </summary> /// <typeparam name="T">Type of object and enumerable.</typeparam> /// <param name="items">Objects to contain in the enumerable.</param> /// <returns>Enumerable of the objects.</returns> public static IEnumerable<T> Enumerify<T>(params T[] items) { var results = Enumerable.Empty<T>(); foreach (var item in items) { results = results.Concat(new T[] { item }); } return results; } /// <summary> /// Returns the items from the enumerable. /// </summary> /// <typeparam name="T">Type of enumerable.</typeparam> /// <param name="enumerable">Container to select from.</param> /// <param name="indeces">Indeces of items to select.</param> /// <returns>Items at the specified indeces.</returns> public static IEnumerable<T> GetElementsAt<T>(this IEnumerable<T> enumerable, params int[] indeces) { var results = Enumerable.Empty<T>(); foreach (var index in indeces) { results = results.Concat(new T[] { enumerable.ElementAt(index) }); } return results; } /// <summary> /// Returns the items from the enumerable. /// </summary> /// <typeparam name="T">Type of enumerable.</typeparam> /// <param name="enumerable">Container to select from.</param> /// <param name="indeces">Indeces of items to select.</param> /// <returns>Items at the specified indeces.</returns> public static IEnumerable<T> GetElementsAt<T>(this IEnumerable<T> enumerable, IEnumerable<int> indeces) { var results = Enumerable.Empty<T>(); foreach (var index in indeces) { results = results.Concat(new T[] { enumerable.ElementAt(index) }); } return results; } /// <summary> /// Splits a collection into subsets, each containing chunkSize elements except the last /// which will contain upto (inclusive) chunkSize elements. /// </summary> /// <typeparam name="T">Type of collection.</typeparam> /// <param name="source">Collection to split.</param> /// <param name="chunkSize">Size of subsets.</param> /// <returns>Enumerable of subsets of the collection.</returns> public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int chunkSize) { if (chunkSize < 1) { throw new ArgumentOutOfRangeException(string.Format("{0} must be a positive integer.", nameof(chunkSize))); } var chunk = new List<T>(); foreach (var item in source) { chunk.Add(item); if (chunk.Count == chunkSize) { yield return chunk; chunk = new List<T>(); } } if (chunk.Count > 0) { yield return chunk; } } /// <summary> /// An action, in enumerable form. /// </summary> /// <param name="action">Action to be performed.</param> /// <returns>An enumerable that always iterates to null.</returns> public static IEnumerable<AlwaysNull> RepeatableFunc(Action action) { while (true) { action(); yield return null; } } /// <summary> /// A function, in enumerable form. /// </summary> /// <typeparam name="TResult">Type of function result.</typeparam> /// <param name="func">Function to be performed.</param> /// <returns>An enumerable that always iterates to the evaluation of the function.</returns> public static IEnumerable<TResult> RepeatableFunc<TResult>(Func<TResult> func) { while (true) { yield return func(); } } /// <summary> /// Performs the cartesian product of two enumerables. /// </summary> /// <typeparam name="T">Type of enumerables.</typeparam> /// <param name="source">First enumerable to select from.</param> /// <param name="other">Second enumerable to select from.</param> /// <returns>An enumerable containing pairs of items from the two enumerables.</returns> public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<T> source, IEnumerable<T> other) { return source.Join(other, x => true, x => true, (x,y) => Enumerable.Empty<T>().Append(x).Append(y)); /* // Alternatively: if (object.ReferenceEquals(null, source) || object.ReferenceEquals(null, other)) { throw new NullReferenceException(); } foreach (var x in source) { foreach (var y in other) { yield return Enumerable.Empty<T>().Append(x).Append(y); } } yield break; */ } /// <summary> /// Pairs an enumerable with itself, returning all distinct pairs. /// </summary> /// <typeparam name="T">Type of enumerable.</typeparam> /// <param name="source">Enumerable collection.</param> /// <returns>Tuples of distinct pairs.</returns> public static IEnumerable<Tuple<T, T>> DistinctSelfTuples<T>(this IEnumerable<T> source) { return source .Select((element, index) => source.Skip(index + 1) .Select(element2 => new Tuple<T, T>(element, element2))) .SelectMany(x => x); } /// <summary> /// Pairs an enumerable with itself generating all distinct pairs, and calls a function on each pair. /// </summary> /// <typeparam name="T">Type of enumerable.</typeparam> /// <typeparam name="TNew">Type of transformed result.</typeparam> /// <param name="source">Enumerable collection.</param> /// <param name="func">Function to call on each pair.</param> /// <returns>Enumerable collection of the transformed pairs.</returns> /// <remarks> /// No need to specify TNew if this is an endomorphism. /// </remarks> public static IEnumerable<TNew> DistinctSelfPairsAction<T, TNew>(this IEnumerable<T> source, Func<T, T, TNew> func) { return source .Select((element, index) => source.Skip(index + 1) .Select(element2 => func(element, element2))) .SelectMany(x => x); } /// <summary> /// Pairs an list with itself, returning all distinct pairs. /// </summary> /// <typeparam name="T">Type of list.</typeparam> /// <param name="source">Collection.</param> /// <returns>Tuples of distinct pairs.</returns> public static IEnumerable<Tuple<T, T>> DistinctSelfTuples<T>(this List<T> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } for (var i = 0; i < source.Count; i++) { for (var j = i + 1; j < source.Count; j++) { yield return new Tuple<T, T>(source[i], source[j]); } } } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using System.Threading.Tasks; using SDKTemplate; using Windows.Graphics.Imaging; using Windows.Media; using Windows.Media.Capture; using Windows.Media.FaceAnalysis; using Windows.Media.MediaProperties; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Shapes; namespace FaceDetectionSample { /// <summary> /// Page for demonstrating FaceDetection on a webcam snapshot. /// </summary> public sealed partial class DetectFacesInWebcam : Page { /// <summary> /// Brush for drawing the bounding box around each detected face. /// </summary> private readonly SolidColorBrush lineBrush = new SolidColorBrush(Windows.UI.Colors.Yellow); /// <summary> /// Thickness of the face bounding box lines. /// </summary> private readonly double lineThickness = 2.0; /// <summary> /// Transparent fill for the bounding box. /// </summary> private readonly SolidColorBrush fillBrush = new SolidColorBrush(Windows.UI.Colors.Transparent); /// <summary> /// Reference back to the "root" page of the app. /// </summary> private MainPage rootPage; /// <summary> /// Holds the current scenario state value. /// </summary> private ScenarioState currentState; /// <summary> /// References a MediaCapture instance; is null when not in Streaming state. /// </summary> private MediaCapture mediaCapture; /// <summary> /// Cache of properties from the current MediaCapture device which is used for capturing the preview frame. /// </summary> private VideoEncodingProperties videoProperties; /// <summary> /// References a FaceDetector instance. /// </summary> private FaceDetector faceDetector; /// <summary> /// Initializes a new instance of the <see cref="DetectFacesInWebcam"/> class. /// </summary> public DetectFacesInWebcam() { this.InitializeComponent(); this.currentState = ScenarioState.Idle; App.Current.Suspending += this.OnSuspending; } /// <summary> /// Values for identifying and controlling scenario states. /// </summary> private enum ScenarioState { /// <summary> /// Display is blank - default state. /// </summary> Idle, /// <summary> /// Webcam is actively engaged and a live video stream is displayed. /// </summary> Streaming, /// <summary> /// Snapshot image has been captured and is being displayed along with detected faces; webcam is not active. /// </summary> Snapshot } /// <summary> /// Responds when we navigate to this page. /// </summary> /// <param name="e">Event data</param> protected override async void OnNavigatedTo(NavigationEventArgs e) { this.rootPage = MainPage.Current; // The 'await' operation can only be used from within an async method but class constructors // cannot be labeled as async, and so we'll initialize FaceDetector here. if (this.faceDetector == null) { this.faceDetector = await FaceDetector.CreateAsync(); } } /// <summary> /// Responds to App Suspend event to stop/release MediaCapture object if it's running and return to Idle state. /// </summary> /// <param name="sender">The source of the Suspending event</param> /// <param name="e">Event data</param> private void OnSuspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) { if (this.currentState == ScenarioState.Streaming) { var deferral = e.SuspendingOperation.GetDeferral(); try { this.ChangeScenarioState(ScenarioState.Idle); } finally { deferral.Complete(); } } } /// <summary> /// Initializes a new MediaCapture instance and starts the Preview streaming to the CamPreview UI element. /// </summary> /// <returns>Async Task object returning true if initialization and streaming were successful and false if an exception occurred.</returns> private async Task<bool> StartWebcamStreaming() { bool successful = true; try { this.mediaCapture = new MediaCapture(); // For this scenario, we only need Video (not microphone) so specify this in the initializer. // NOTE: the appxmanifest only declares "webcam" under capabilities and if this is changed to include // microphone (default constructor) you must add "microphone" to the manifest or initialization will fail. MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings(); settings.StreamingCaptureMode = StreamingCaptureMode.Video; await this.mediaCapture.InitializeAsync(settings); this.mediaCapture.CameraStreamStateChanged += this.MediaCapture_CameraStreamStateChanged; // Cache the media properties as we'll need them later. var deviceController = this.mediaCapture.VideoDeviceController; this.videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; // Immediately start streaming to our CaptureElement UI. // NOTE: CaptureElement's Source must be set before streaming is started. this.CamPreview.Source = this.mediaCapture; await this.mediaCapture.StartPreviewAsync(); } catch (System.UnauthorizedAccessException) { // If the user has disabled their webcam this exception is thrown; provide a descriptive message to inform the user of this fact. this.rootPage.NotifyUser("Webcam is disabled or access to the webcam is disabled for this app.\nEnsure Privacy Settings allow webcam usage.", NotifyType.ErrorMessage); successful = false; } catch (Exception ex) { this.rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage); successful = false; } return successful; } /// <summary> /// Safely stops webcam streaming (if running) and releases MediaCapture object. /// </summary> private async void ShutdownWebCam() { if (this.mediaCapture != null) { if (this.mediaCapture.CameraStreamState == Windows.Media.Devices.CameraStreamState.Streaming) { await this.mediaCapture.StopPreviewAsync(); } this.mediaCapture.Dispose(); } this.CamPreview.Source = null; this.mediaCapture = null; } /// <summary> /// Captures a single frame from the running webcam stream and executes the FaceDetector on the image. If successful calls SetupVisualization to display the results. /// </summary> /// <returns>Async Task object returning true if the capture was successful and false if an exception occurred.</returns> private async Task<bool> TakeSnapshotAndFindFaces() { bool successful = true; try { if (this.currentState != ScenarioState.Streaming) { return false; } WriteableBitmap displaySource = null; IList<DetectedFace> faces = null; // Create a VideoFrame object specifying the pixel format we want our capture image to be (NV12 bitmap in this case). // GetPreviewFrame will convert the native webcam frame into this format. const BitmapPixelFormat InputPixelFormat = BitmapPixelFormat.Nv12; using (VideoFrame previewFrame = new VideoFrame(InputPixelFormat, (int)this.videoProperties.Width, (int)this.videoProperties.Height)) { await this.mediaCapture.GetPreviewFrameAsync(previewFrame); // The returned VideoFrame should be in the supported NV12 format but we need to verify this. if (FaceDetector.IsBitmapPixelFormatSupported(previewFrame.SoftwareBitmap.BitmapPixelFormat)) { faces = await this.faceDetector.DetectFacesAsync(previewFrame.SoftwareBitmap); } else { this.rootPage.NotifyUser("PixelFormat '" + InputPixelFormat.ToString() + "' is not supported by FaceDetector", NotifyType.ErrorMessage); } // Create a WritableBitmap for our visualization display; copy the original bitmap pixels to wb's buffer. // Note that WriteableBitmap doesn't support NV12 and we have to convert it to 32-bit BGRA. using (SoftwareBitmap convertedSource = SoftwareBitmap.Convert(previewFrame.SoftwareBitmap, BitmapPixelFormat.Bgra8)) { displaySource = new WriteableBitmap(convertedSource.PixelWidth, convertedSource.PixelHeight); convertedSource.CopyToBuffer(displaySource.PixelBuffer); } // Create our display using the available image and face results. this.SetupVisualization(displaySource, faces); } } catch (Exception ex) { this.rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage); successful = false; } return successful; } /// <summary> /// Takes the webcam image and FaceDetector results and assembles the visualization onto the Canvas. /// </summary> /// <param name="displaySource">Bitmap object holding the image we're going to display</param> /// <param name="foundFaces">List of detected faces; output from FaceDetector</param> private void SetupVisualization(WriteableBitmap displaySource, IList<DetectedFace> foundFaces) { ImageBrush brush = new ImageBrush(); brush.ImageSource = displaySource; brush.Stretch = Stretch.Fill; this.SnapshotCanvas.Background = brush; if (foundFaces != null) { double widthScale = displaySource.PixelWidth / this.SnapshotCanvas.ActualWidth; double heightScale = displaySource.PixelHeight / this.SnapshotCanvas.ActualHeight; foreach (DetectedFace face in foundFaces) { // Create a rectangle element for displaying the face box but since we're using a Canvas // we must scale the rectangles according to the image's actual size. // The original FaceBox values are saved in the Rectangle's Tag field so we can update the // boxes when the Canvas is resized. Rectangle box = new Rectangle(); box.Tag = face.FaceBox; box.Width = (uint)(face.FaceBox.Width / widthScale); box.Height = (uint)(face.FaceBox.Height / heightScale); box.Fill = this.fillBrush; box.Stroke = this.lineBrush; box.StrokeThickness = this.lineThickness; box.Margin = new Thickness((uint)(face.FaceBox.X / widthScale), (uint)(face.FaceBox.Y / heightScale), 0, 0); this.SnapshotCanvas.Children.Add(box); } } string message; if (foundFaces == null || foundFaces.Count == 0) { message = "Didn't find any human faces in the image"; } else if (foundFaces.Count == 1) { message = "Found a human face in the image"; } else { message = "Found " + foundFaces.Count + " human faces in the image"; } this.rootPage.NotifyUser(message, NotifyType.StatusMessage); } /// <summary> /// Manages the scenario's internal state. Invokes the internal methods and updates the UI according to the /// passed in state value. Handles failures and resets the state if necessary. /// </summary> /// <param name="newState">State to switch to</param> private async void ChangeScenarioState(ScenarioState newState) { switch (newState) { case ScenarioState.Idle: this.ShutdownWebCam(); this.SnapshotCanvas.Background = null; this.SnapshotCanvas.Children.Clear(); this.CameraSnapshotButton.IsEnabled = false; this.CameraStreamingButton.Content = "Start Streaming"; this.CameraSnapshotButton.Content = "Take Snapshot"; this.currentState = newState; break; case ScenarioState.Streaming: if (!await this.StartWebcamStreaming()) { this.ChangeScenarioState(ScenarioState.Idle); break; } this.SnapshotCanvas.Background = null; this.SnapshotCanvas.Children.Clear(); this.CameraSnapshotButton.IsEnabled = true; this.CameraStreamingButton.Content = "Stop Streaming"; this.CameraSnapshotButton.Content = "Take Snapshot"; this.currentState = newState; break; case ScenarioState.Snapshot: if (!await this.TakeSnapshotAndFindFaces()) { this.ChangeScenarioState(ScenarioState.Idle); break; } this.ShutdownWebCam(); this.CameraSnapshotButton.IsEnabled = true; this.CameraStreamingButton.Content = "Start Streaming"; this.CameraSnapshotButton.Content = "Clear Display"; this.currentState = newState; break; } } /// <summary> /// Handles MediaCapture changes by shutting down streaming and returning to Idle state. /// </summary> /// <param name="sender">The source of the event, i.e. our MediaCapture object</param> /// <param name="args">Event data</param> private void MediaCapture_CameraStreamStateChanged(MediaCapture sender, object args) { // MediaCapture is not Agile and so we cannot invoke it's methods on this caller's thread // and instead need to schedule the state change on the UI thread. var ignored = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ChangeScenarioState(ScenarioState.Idle); }); } /// <summary> /// Handles "streaming" button clicks to start/stop webcam streaming. /// </summary> /// <param name="sender">Button user clicked</param> /// <param name="e">Event data</param> private void CameraStreamingButton_Click(object sender, RoutedEventArgs e) { if (this.currentState == ScenarioState.Streaming) { this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage); this.ChangeScenarioState(ScenarioState.Idle); } else { this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage); this.ChangeScenarioState(ScenarioState.Streaming); } } /// <summary> /// Handles "snapshot" button clicks to take a snapshot or clear the current display. /// </summary> /// <param name="sender">Button user clicked</param> /// <param name="e">Event data</param> private void CameraSnapshotButton_Click(object sender, RoutedEventArgs e) { if (this.currentState == ScenarioState.Streaming) { this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage); this.ChangeScenarioState(ScenarioState.Snapshot); } else { this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage); this.ChangeScenarioState(ScenarioState.Idle); } } /// <summary> /// Updates any existing face bounding boxes in response to changes in the size of the Canvas. /// </summary> /// <param name="sender">Canvas whose size has changed</param> /// <param name="e">Event data</param> private void SnapshotCanvas_SizeChanged(object sender, SizeChangedEventArgs e) { try { // If the Canvas is resized we must recompute a new scaling factor and // apply it to each face box. if (this.currentState == ScenarioState.Snapshot && this.SnapshotCanvas.Background != null) { WriteableBitmap displaySource = (this.SnapshotCanvas.Background as ImageBrush).ImageSource as WriteableBitmap; double widthScale = displaySource.PixelWidth / this.SnapshotCanvas.ActualWidth; double heightScale = displaySource.PixelHeight / this.SnapshotCanvas.ActualHeight; foreach (var item in this.SnapshotCanvas.Children) { Rectangle box = item as Rectangle; if (box == null) { continue; } // We saved the original size of the face box in the rectangles Tag field. BitmapBounds faceBounds = (BitmapBounds)box.Tag; box.Width = (uint)(faceBounds.Width / widthScale); box.Height = (uint)(faceBounds.Height / heightScale); box.Margin = new Thickness((uint)(faceBounds.X / widthScale), (uint)(faceBounds.Y / heightScale), 0, 0); } } } catch (Exception ex) { this.rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage); } } } }
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 LabTempResultadoEncabezado class. /// </summary> [Serializable] public partial class LabTempResultadoEncabezadoCollection : ActiveList<LabTempResultadoEncabezado, LabTempResultadoEncabezadoCollection> { public LabTempResultadoEncabezadoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>LabTempResultadoEncabezadoCollection</returns> public LabTempResultadoEncabezadoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { LabTempResultadoEncabezado 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 LAB_Temp_ResultadoEncabezado table. /// </summary> [Serializable] public partial class LabTempResultadoEncabezado : ActiveRecord<LabTempResultadoEncabezado>, IActiveRecord { #region .ctors and Default Settings public LabTempResultadoEncabezado() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public LabTempResultadoEncabezado(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public LabTempResultadoEncabezado(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public LabTempResultadoEncabezado(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("LAB_Temp_ResultadoEncabezado", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdProtocolo = new TableSchema.TableColumn(schema); colvarIdProtocolo.ColumnName = "idProtocolo"; colvarIdProtocolo.DataType = DbType.Int32; colvarIdProtocolo.MaxLength = 0; colvarIdProtocolo.AutoIncrement = false; colvarIdProtocolo.IsNullable = false; colvarIdProtocolo.IsPrimaryKey = true; colvarIdProtocolo.IsForeignKey = false; colvarIdProtocolo.IsReadOnly = false; colvarIdProtocolo.DefaultSetting = @""; colvarIdProtocolo.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdProtocolo); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = false; colvarIdEfector.IsPrimaryKey = true; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarApellido = new TableSchema.TableColumn(schema); colvarApellido.ColumnName = "apellido"; colvarApellido.DataType = DbType.String; colvarApellido.MaxLength = 100; colvarApellido.AutoIncrement = false; colvarApellido.IsNullable = false; colvarApellido.IsPrimaryKey = false; colvarApellido.IsForeignKey = false; colvarApellido.IsReadOnly = false; colvarApellido.DefaultSetting = @""; colvarApellido.ForeignKeyTableName = ""; schema.Columns.Add(colvarApellido); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 100; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema); colvarEdad.ColumnName = "edad"; colvarEdad.DataType = DbType.Int32; colvarEdad.MaxLength = 0; colvarEdad.AutoIncrement = false; colvarEdad.IsNullable = false; colvarEdad.IsPrimaryKey = false; colvarEdad.IsForeignKey = false; colvarEdad.IsReadOnly = false; colvarEdad.DefaultSetting = @""; colvarEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarEdad); TableSchema.TableColumn colvarUnidadEdad = new TableSchema.TableColumn(schema); colvarUnidadEdad.ColumnName = "unidadEdad"; colvarUnidadEdad.DataType = DbType.AnsiString; colvarUnidadEdad.MaxLength = 5; colvarUnidadEdad.AutoIncrement = false; colvarUnidadEdad.IsNullable = true; colvarUnidadEdad.IsPrimaryKey = false; colvarUnidadEdad.IsForeignKey = false; colvarUnidadEdad.IsReadOnly = false; colvarUnidadEdad.DefaultSetting = @""; colvarUnidadEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarUnidadEdad); TableSchema.TableColumn colvarFechaNacimiento = new TableSchema.TableColumn(schema); colvarFechaNacimiento.ColumnName = "fechaNacimiento"; colvarFechaNacimiento.DataType = DbType.AnsiString; colvarFechaNacimiento.MaxLength = 10; colvarFechaNacimiento.AutoIncrement = false; colvarFechaNacimiento.IsNullable = true; colvarFechaNacimiento.IsPrimaryKey = false; colvarFechaNacimiento.IsForeignKey = false; colvarFechaNacimiento.IsReadOnly = false; colvarFechaNacimiento.DefaultSetting = @""; colvarFechaNacimiento.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaNacimiento); TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema); colvarSexo.ColumnName = "sexo"; colvarSexo.DataType = DbType.String; colvarSexo.MaxLength = 1; colvarSexo.AutoIncrement = false; colvarSexo.IsNullable = false; colvarSexo.IsPrimaryKey = false; colvarSexo.IsForeignKey = false; colvarSexo.IsReadOnly = false; colvarSexo.DefaultSetting = @""; colvarSexo.ForeignKeyTableName = ""; schema.Columns.Add(colvarSexo); TableSchema.TableColumn colvarNumeroDocumento = new TableSchema.TableColumn(schema); colvarNumeroDocumento.ColumnName = "numeroDocumento"; colvarNumeroDocumento.DataType = DbType.Int32; colvarNumeroDocumento.MaxLength = 0; colvarNumeroDocumento.AutoIncrement = false; colvarNumeroDocumento.IsNullable = false; colvarNumeroDocumento.IsPrimaryKey = false; colvarNumeroDocumento.IsForeignKey = false; colvarNumeroDocumento.IsReadOnly = false; colvarNumeroDocumento.DefaultSetting = @""; colvarNumeroDocumento.ForeignKeyTableName = ""; schema.Columns.Add(colvarNumeroDocumento); TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema); colvarFecha.ColumnName = "fecha"; colvarFecha.DataType = DbType.AnsiString; colvarFecha.MaxLength = 10; colvarFecha.AutoIncrement = false; colvarFecha.IsNullable = true; colvarFecha.IsPrimaryKey = false; colvarFecha.IsForeignKey = false; colvarFecha.IsReadOnly = false; colvarFecha.DefaultSetting = @""; colvarFecha.ForeignKeyTableName = ""; schema.Columns.Add(colvarFecha); TableSchema.TableColumn colvarFecha1 = new TableSchema.TableColumn(schema); colvarFecha1.ColumnName = "fecha1"; colvarFecha1.DataType = DbType.DateTime; colvarFecha1.MaxLength = 0; colvarFecha1.AutoIncrement = false; colvarFecha1.IsNullable = false; colvarFecha1.IsPrimaryKey = false; colvarFecha1.IsForeignKey = false; colvarFecha1.IsReadOnly = false; colvarFecha1.DefaultSetting = @""; colvarFecha1.ForeignKeyTableName = ""; schema.Columns.Add(colvarFecha1); TableSchema.TableColumn colvarDomicilio = new TableSchema.TableColumn(schema); colvarDomicilio.ColumnName = "domicilio"; colvarDomicilio.DataType = DbType.String; colvarDomicilio.MaxLength = 261; colvarDomicilio.AutoIncrement = false; colvarDomicilio.IsNullable = true; colvarDomicilio.IsPrimaryKey = false; colvarDomicilio.IsForeignKey = false; colvarDomicilio.IsReadOnly = false; colvarDomicilio.DefaultSetting = @""; colvarDomicilio.ForeignKeyTableName = ""; schema.Columns.Add(colvarDomicilio); TableSchema.TableColumn colvarHc = new TableSchema.TableColumn(schema); colvarHc.ColumnName = "HC"; colvarHc.DataType = DbType.Int32; colvarHc.MaxLength = 0; colvarHc.AutoIncrement = false; colvarHc.IsNullable = false; colvarHc.IsPrimaryKey = false; colvarHc.IsForeignKey = false; colvarHc.IsReadOnly = false; colvarHc.DefaultSetting = @""; colvarHc.ForeignKeyTableName = ""; schema.Columns.Add(colvarHc); TableSchema.TableColumn colvarPrioridad = new TableSchema.TableColumn(schema); colvarPrioridad.ColumnName = "prioridad"; colvarPrioridad.DataType = DbType.String; colvarPrioridad.MaxLength = 50; colvarPrioridad.AutoIncrement = false; colvarPrioridad.IsNullable = false; colvarPrioridad.IsPrimaryKey = false; colvarPrioridad.IsForeignKey = false; colvarPrioridad.IsReadOnly = false; colvarPrioridad.DefaultSetting = @""; colvarPrioridad.ForeignKeyTableName = ""; schema.Columns.Add(colvarPrioridad); TableSchema.TableColumn colvarOrigen = new TableSchema.TableColumn(schema); colvarOrigen.ColumnName = "origen"; colvarOrigen.DataType = DbType.String; colvarOrigen.MaxLength = 50; colvarOrigen.AutoIncrement = false; colvarOrigen.IsNullable = false; colvarOrigen.IsPrimaryKey = false; colvarOrigen.IsForeignKey = false; colvarOrigen.IsReadOnly = false; colvarOrigen.DefaultSetting = @""; colvarOrigen.ForeignKeyTableName = ""; schema.Columns.Add(colvarOrigen); TableSchema.TableColumn colvarNumero = new TableSchema.TableColumn(schema); colvarNumero.ColumnName = "numero"; colvarNumero.DataType = DbType.AnsiString; colvarNumero.MaxLength = 50; colvarNumero.AutoIncrement = false; colvarNumero.IsNullable = true; colvarNumero.IsPrimaryKey = false; colvarNumero.IsForeignKey = false; colvarNumero.IsReadOnly = false; colvarNumero.DefaultSetting = @""; colvarNumero.ForeignKeyTableName = ""; schema.Columns.Add(colvarNumero); TableSchema.TableColumn colvarHiv = new TableSchema.TableColumn(schema); colvarHiv.ColumnName = "hiv"; colvarHiv.DataType = DbType.Boolean; colvarHiv.MaxLength = 0; colvarHiv.AutoIncrement = false; colvarHiv.IsNullable = true; colvarHiv.IsPrimaryKey = false; colvarHiv.IsForeignKey = false; colvarHiv.IsReadOnly = false; colvarHiv.DefaultSetting = @""; colvarHiv.ForeignKeyTableName = ""; schema.Columns.Add(colvarHiv); TableSchema.TableColumn colvarSolicitante = new TableSchema.TableColumn(schema); colvarSolicitante.ColumnName = "solicitante"; colvarSolicitante.DataType = DbType.String; colvarSolicitante.MaxLength = 205; colvarSolicitante.AutoIncrement = false; colvarSolicitante.IsNullable = true; colvarSolicitante.IsPrimaryKey = false; colvarSolicitante.IsForeignKey = false; colvarSolicitante.IsReadOnly = false; colvarSolicitante.DefaultSetting = @""; colvarSolicitante.ForeignKeyTableName = ""; schema.Columns.Add(colvarSolicitante); TableSchema.TableColumn colvarSector = new TableSchema.TableColumn(schema); colvarSector.ColumnName = "sector"; colvarSector.DataType = DbType.AnsiString; colvarSector.MaxLength = 50; colvarSector.AutoIncrement = false; colvarSector.IsNullable = false; colvarSector.IsPrimaryKey = false; colvarSector.IsForeignKey = false; colvarSector.IsReadOnly = false; colvarSector.DefaultSetting = @""; colvarSector.ForeignKeyTableName = ""; schema.Columns.Add(colvarSector); TableSchema.TableColumn colvarSala = new TableSchema.TableColumn(schema); colvarSala.ColumnName = "sala"; colvarSala.DataType = DbType.AnsiString; colvarSala.MaxLength = 50; colvarSala.AutoIncrement = false; colvarSala.IsNullable = false; colvarSala.IsPrimaryKey = false; colvarSala.IsForeignKey = false; colvarSala.IsReadOnly = false; colvarSala.DefaultSetting = @""; colvarSala.ForeignKeyTableName = ""; schema.Columns.Add(colvarSala); TableSchema.TableColumn colvarCama = new TableSchema.TableColumn(schema); colvarCama.ColumnName = "cama"; colvarCama.DataType = DbType.AnsiString; colvarCama.MaxLength = 50; colvarCama.AutoIncrement = false; colvarCama.IsNullable = false; colvarCama.IsPrimaryKey = false; colvarCama.IsForeignKey = false; colvarCama.IsReadOnly = false; colvarCama.DefaultSetting = @""; colvarCama.ForeignKeyTableName = ""; schema.Columns.Add(colvarCama); TableSchema.TableColumn colvarEmbarazo = new TableSchema.TableColumn(schema); colvarEmbarazo.ColumnName = "embarazo"; colvarEmbarazo.DataType = DbType.AnsiString; colvarEmbarazo.MaxLength = 1; colvarEmbarazo.AutoIncrement = false; colvarEmbarazo.IsNullable = false; colvarEmbarazo.IsPrimaryKey = false; colvarEmbarazo.IsForeignKey = false; colvarEmbarazo.IsReadOnly = false; colvarEmbarazo.DefaultSetting = @""; colvarEmbarazo.ForeignKeyTableName = ""; schema.Columns.Add(colvarEmbarazo); TableSchema.TableColumn colvarEfectorSolicitante = new TableSchema.TableColumn(schema); colvarEfectorSolicitante.ColumnName = "EfectorSolicitante"; colvarEfectorSolicitante.DataType = DbType.String; colvarEfectorSolicitante.MaxLength = 100; colvarEfectorSolicitante.AutoIncrement = false; colvarEfectorSolicitante.IsNullable = false; colvarEfectorSolicitante.IsPrimaryKey = false; colvarEfectorSolicitante.IsForeignKey = false; colvarEfectorSolicitante.IsReadOnly = false; colvarEfectorSolicitante.DefaultSetting = @""; colvarEfectorSolicitante.ForeignKeyTableName = ""; schema.Columns.Add(colvarEfectorSolicitante); TableSchema.TableColumn colvarIdSolicitudScreening = new TableSchema.TableColumn(schema); colvarIdSolicitudScreening.ColumnName = "idSolicitudScreening"; colvarIdSolicitudScreening.DataType = DbType.Int32; colvarIdSolicitudScreening.MaxLength = 0; colvarIdSolicitudScreening.AutoIncrement = false; colvarIdSolicitudScreening.IsNullable = true; colvarIdSolicitudScreening.IsPrimaryKey = false; colvarIdSolicitudScreening.IsForeignKey = false; colvarIdSolicitudScreening.IsReadOnly = false; colvarIdSolicitudScreening.DefaultSetting = @""; colvarIdSolicitudScreening.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdSolicitudScreening); TableSchema.TableColumn colvarFechaRecibeScreening = new TableSchema.TableColumn(schema); colvarFechaRecibeScreening.ColumnName = "fechaRecibeScreening"; colvarFechaRecibeScreening.DataType = DbType.DateTime; colvarFechaRecibeScreening.MaxLength = 0; colvarFechaRecibeScreening.AutoIncrement = false; colvarFechaRecibeScreening.IsNullable = true; colvarFechaRecibeScreening.IsPrimaryKey = false; colvarFechaRecibeScreening.IsForeignKey = false; colvarFechaRecibeScreening.IsReadOnly = false; colvarFechaRecibeScreening.DefaultSetting = @""; colvarFechaRecibeScreening.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaRecibeScreening); TableSchema.TableColumn colvarObservacionesResultados = new TableSchema.TableColumn(schema); colvarObservacionesResultados.ColumnName = "observacionesResultados"; colvarObservacionesResultados.DataType = DbType.String; colvarObservacionesResultados.MaxLength = 4000; colvarObservacionesResultados.AutoIncrement = false; colvarObservacionesResultados.IsNullable = true; colvarObservacionesResultados.IsPrimaryKey = false; colvarObservacionesResultados.IsForeignKey = false; colvarObservacionesResultados.IsReadOnly = false; colvarObservacionesResultados.DefaultSetting = @""; colvarObservacionesResultados.ForeignKeyTableName = ""; schema.Columns.Add(colvarObservacionesResultados); TableSchema.TableColumn colvarTipoMuestra = new TableSchema.TableColumn(schema); colvarTipoMuestra.ColumnName = "tipoMuestra"; colvarTipoMuestra.DataType = DbType.String; colvarTipoMuestra.MaxLength = 500; colvarTipoMuestra.AutoIncrement = false; colvarTipoMuestra.IsNullable = true; colvarTipoMuestra.IsPrimaryKey = false; colvarTipoMuestra.IsForeignKey = false; colvarTipoMuestra.IsReadOnly = false; colvarTipoMuestra.DefaultSetting = @""; colvarTipoMuestra.ForeignKeyTableName = ""; schema.Columns.Add(colvarTipoMuestra); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("LAB_Temp_ResultadoEncabezado",schema); } } #endregion #region Props [XmlAttribute("IdProtocolo")] [Bindable(true)] public int IdProtocolo { get { return GetColumnValue<int>(Columns.IdProtocolo); } set { SetColumnValue(Columns.IdProtocolo, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int IdEfector { get { return GetColumnValue<int>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("Apellido")] [Bindable(true)] public string Apellido { get { return GetColumnValue<string>(Columns.Apellido); } set { SetColumnValue(Columns.Apellido, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("Edad")] [Bindable(true)] public int Edad { get { return GetColumnValue<int>(Columns.Edad); } set { SetColumnValue(Columns.Edad, value); } } [XmlAttribute("UnidadEdad")] [Bindable(true)] public string UnidadEdad { get { return GetColumnValue<string>(Columns.UnidadEdad); } set { SetColumnValue(Columns.UnidadEdad, value); } } [XmlAttribute("FechaNacimiento")] [Bindable(true)] public string FechaNacimiento { get { return GetColumnValue<string>(Columns.FechaNacimiento); } set { SetColumnValue(Columns.FechaNacimiento, value); } } [XmlAttribute("Sexo")] [Bindable(true)] public string Sexo { get { return GetColumnValue<string>(Columns.Sexo); } set { SetColumnValue(Columns.Sexo, value); } } [XmlAttribute("NumeroDocumento")] [Bindable(true)] public int NumeroDocumento { get { return GetColumnValue<int>(Columns.NumeroDocumento); } set { SetColumnValue(Columns.NumeroDocumento, value); } } [XmlAttribute("Fecha")] [Bindable(true)] public string Fecha { get { return GetColumnValue<string>(Columns.Fecha); } set { SetColumnValue(Columns.Fecha, value); } } [XmlAttribute("Fecha1")] [Bindable(true)] public DateTime Fecha1 { get { return GetColumnValue<DateTime>(Columns.Fecha1); } set { SetColumnValue(Columns.Fecha1, value); } } [XmlAttribute("Domicilio")] [Bindable(true)] public string Domicilio { get { return GetColumnValue<string>(Columns.Domicilio); } set { SetColumnValue(Columns.Domicilio, value); } } [XmlAttribute("Hc")] [Bindable(true)] public int Hc { get { return GetColumnValue<int>(Columns.Hc); } set { SetColumnValue(Columns.Hc, value); } } [XmlAttribute("Prioridad")] [Bindable(true)] public string Prioridad { get { return GetColumnValue<string>(Columns.Prioridad); } set { SetColumnValue(Columns.Prioridad, value); } } [XmlAttribute("Origen")] [Bindable(true)] public string Origen { get { return GetColumnValue<string>(Columns.Origen); } set { SetColumnValue(Columns.Origen, value); } } [XmlAttribute("Numero")] [Bindable(true)] public string Numero { get { return GetColumnValue<string>(Columns.Numero); } set { SetColumnValue(Columns.Numero, value); } } [XmlAttribute("Hiv")] [Bindable(true)] public bool? Hiv { get { return GetColumnValue<bool?>(Columns.Hiv); } set { SetColumnValue(Columns.Hiv, value); } } [XmlAttribute("Solicitante")] [Bindable(true)] public string Solicitante { get { return GetColumnValue<string>(Columns.Solicitante); } set { SetColumnValue(Columns.Solicitante, value); } } [XmlAttribute("Sector")] [Bindable(true)] public string Sector { get { return GetColumnValue<string>(Columns.Sector); } set { SetColumnValue(Columns.Sector, value); } } [XmlAttribute("Sala")] [Bindable(true)] public string Sala { get { return GetColumnValue<string>(Columns.Sala); } set { SetColumnValue(Columns.Sala, value); } } [XmlAttribute("Cama")] [Bindable(true)] public string Cama { get { return GetColumnValue<string>(Columns.Cama); } set { SetColumnValue(Columns.Cama, value); } } [XmlAttribute("Embarazo")] [Bindable(true)] public string Embarazo { get { return GetColumnValue<string>(Columns.Embarazo); } set { SetColumnValue(Columns.Embarazo, value); } } [XmlAttribute("EfectorSolicitante")] [Bindable(true)] public string EfectorSolicitante { get { return GetColumnValue<string>(Columns.EfectorSolicitante); } set { SetColumnValue(Columns.EfectorSolicitante, value); } } [XmlAttribute("IdSolicitudScreening")] [Bindable(true)] public int? IdSolicitudScreening { get { return GetColumnValue<int?>(Columns.IdSolicitudScreening); } set { SetColumnValue(Columns.IdSolicitudScreening, value); } } [XmlAttribute("FechaRecibeScreening")] [Bindable(true)] public DateTime? FechaRecibeScreening { get { return GetColumnValue<DateTime?>(Columns.FechaRecibeScreening); } set { SetColumnValue(Columns.FechaRecibeScreening, value); } } [XmlAttribute("ObservacionesResultados")] [Bindable(true)] public string ObservacionesResultados { get { return GetColumnValue<string>(Columns.ObservacionesResultados); } set { SetColumnValue(Columns.ObservacionesResultados, value); } } [XmlAttribute("TipoMuestra")] [Bindable(true)] public string TipoMuestra { get { return GetColumnValue<string>(Columns.TipoMuestra); } set { SetColumnValue(Columns.TipoMuestra, value); } } #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(int varIdProtocolo,int varIdEfector,string varApellido,string varNombre,int varEdad,string varUnidadEdad,string varFechaNacimiento,string varSexo,int varNumeroDocumento,string varFecha,DateTime varFecha1,string varDomicilio,int varHc,string varPrioridad,string varOrigen,string varNumero,bool? varHiv,string varSolicitante,string varSector,string varSala,string varCama,string varEmbarazo,string varEfectorSolicitante,int? varIdSolicitudScreening,DateTime? varFechaRecibeScreening,string varObservacionesResultados,string varTipoMuestra) { LabTempResultadoEncabezado item = new LabTempResultadoEncabezado(); item.IdProtocolo = varIdProtocolo; item.IdEfector = varIdEfector; item.Apellido = varApellido; item.Nombre = varNombre; item.Edad = varEdad; item.UnidadEdad = varUnidadEdad; item.FechaNacimiento = varFechaNacimiento; item.Sexo = varSexo; item.NumeroDocumento = varNumeroDocumento; item.Fecha = varFecha; item.Fecha1 = varFecha1; item.Domicilio = varDomicilio; item.Hc = varHc; item.Prioridad = varPrioridad; item.Origen = varOrigen; item.Numero = varNumero; item.Hiv = varHiv; item.Solicitante = varSolicitante; item.Sector = varSector; item.Sala = varSala; item.Cama = varCama; item.Embarazo = varEmbarazo; item.EfectorSolicitante = varEfectorSolicitante; item.IdSolicitudScreening = varIdSolicitudScreening; item.FechaRecibeScreening = varFechaRecibeScreening; item.ObservacionesResultados = varObservacionesResultados; item.TipoMuestra = varTipoMuestra; 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 varIdProtocolo,int varIdEfector,string varApellido,string varNombre,int varEdad,string varUnidadEdad,string varFechaNacimiento,string varSexo,int varNumeroDocumento,string varFecha,DateTime varFecha1,string varDomicilio,int varHc,string varPrioridad,string varOrigen,string varNumero,bool? varHiv,string varSolicitante,string varSector,string varSala,string varCama,string varEmbarazo,string varEfectorSolicitante,int? varIdSolicitudScreening,DateTime? varFechaRecibeScreening,string varObservacionesResultados,string varTipoMuestra) { LabTempResultadoEncabezado item = new LabTempResultadoEncabezado(); item.IdProtocolo = varIdProtocolo; item.IdEfector = varIdEfector; item.Apellido = varApellido; item.Nombre = varNombre; item.Edad = varEdad; item.UnidadEdad = varUnidadEdad; item.FechaNacimiento = varFechaNacimiento; item.Sexo = varSexo; item.NumeroDocumento = varNumeroDocumento; item.Fecha = varFecha; item.Fecha1 = varFecha1; item.Domicilio = varDomicilio; item.Hc = varHc; item.Prioridad = varPrioridad; item.Origen = varOrigen; item.Numero = varNumero; item.Hiv = varHiv; item.Solicitante = varSolicitante; item.Sector = varSector; item.Sala = varSala; item.Cama = varCama; item.Embarazo = varEmbarazo; item.EfectorSolicitante = varEfectorSolicitante; item.IdSolicitudScreening = varIdSolicitudScreening; item.FechaRecibeScreening = varFechaRecibeScreening; item.ObservacionesResultados = varObservacionesResultados; item.TipoMuestra = varTipoMuestra; 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 IdProtocoloColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn ApellidoColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn EdadColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn UnidadEdadColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn FechaNacimientoColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn SexoColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn NumeroDocumentoColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn FechaColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn Fecha1Column { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn DomicilioColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn HcColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn PrioridadColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn OrigenColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn NumeroColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn HivColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn SolicitanteColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn SectorColumn { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn SalaColumn { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn CamaColumn { get { return Schema.Columns[20]; } } public static TableSchema.TableColumn EmbarazoColumn { get { return Schema.Columns[21]; } } public static TableSchema.TableColumn EfectorSolicitanteColumn { get { return Schema.Columns[22]; } } public static TableSchema.TableColumn IdSolicitudScreeningColumn { get { return Schema.Columns[23]; } } public static TableSchema.TableColumn FechaRecibeScreeningColumn { get { return Schema.Columns[24]; } } public static TableSchema.TableColumn ObservacionesResultadosColumn { get { return Schema.Columns[25]; } } public static TableSchema.TableColumn TipoMuestraColumn { get { return Schema.Columns[26]; } } #endregion #region Columns Struct public struct Columns { public static string IdProtocolo = @"idProtocolo"; public static string IdEfector = @"idEfector"; public static string Apellido = @"apellido"; public static string Nombre = @"nombre"; public static string Edad = @"edad"; public static string UnidadEdad = @"unidadEdad"; public static string FechaNacimiento = @"fechaNacimiento"; public static string Sexo = @"sexo"; public static string NumeroDocumento = @"numeroDocumento"; public static string Fecha = @"fecha"; public static string Fecha1 = @"fecha1"; public static string Domicilio = @"domicilio"; public static string Hc = @"HC"; public static string Prioridad = @"prioridad"; public static string Origen = @"origen"; public static string Numero = @"numero"; public static string Hiv = @"hiv"; public static string Solicitante = @"solicitante"; public static string Sector = @"sector"; public static string Sala = @"sala"; public static string Cama = @"cama"; public static string Embarazo = @"embarazo"; public static string EfectorSolicitante = @"EfectorSolicitante"; public static string IdSolicitudScreening = @"idSolicitudScreening"; public static string FechaRecibeScreening = @"fechaRecibeScreening"; public static string ObservacionesResultados = @"observacionesResultados"; public static string TipoMuestra = @"tipoMuestra"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Collections.Generic; using AT_Utils.UI; using UnityEngine; using UnityEngine.UI; namespace CC.UI { public class AddTankControl : TankManagerUIPart { public enum VolumeUnits { CUBIC_METERS, PARTS } private static readonly Dictionary<VolumeUnits, string> unitNames = new Dictionary<VolumeUnits, string> { { VolumeUnits.CUBIC_METERS, "m3" }, { VolumeUnits.PARTS, "%" } }; private static readonly int numUnits = Enum.GetNames(typeof(VolumeUnits)).Length; public Dropdown tankTypeDropdown; public TooltipTrigger tankTypeTooltip; public InputField volumeField; public Button unitsSwitchButton, maxVolumeButton, halfVolumeButton, addButton; public Text unitsLabel; public Colorizer volumeFieldColorizer; public TooltipTrigger volumeFieldTooltip; public ITankManager tankManager; public VolumeUnits currentUnits = VolumeUnits.CUBIC_METERS; public void SetTankManager(ITankManager newTankManager) { if(newTankManager == tankManager) return; tankManager = newTankManager; if(tankManager == null) return; UpdateTankTypes(); } private void Awake() { updateUnitsLabel(); tankTypeDropdown.onValueChanged.AddListener(updateTankTypeDropdownTooltip); volumeField.onValueChanged.AddListener(onVolumeChange); unitsSwitchButton.onClick.AddListener(onUnitsSwitch); maxVolumeButton.onClick.AddListener(setMaxVolume); halfVolumeButton.onClick.AddListener(setHalfVolume); addButton.onClick.AddListener(addTank); volumeNotOk("Enter the volume to create a new tank"); } private void OnDestroy() { tankTypeDropdown.onValueChanged.RemoveAllListeners(); volumeField.onValueChanged.RemoveAllListeners(); unitsSwitchButton.onClick.RemoveAllListeners(); maxVolumeButton.onClick.RemoveAllListeners(); halfVolumeButton.onClick.RemoveAllListeners(); addButton.onClick.RemoveAllListeners(); } private float partsToVolume(float value) => tankManager.AvailableVolume * value; private float volumeToParts(float value) => tankManager.AvailableVolume > 0 ? value / tankManager.AvailableVolume : 0; private string tankType => tankManager.SupportedTypes[tankTypeDropdown.value]; private void onUnitsSwitch() { var oldUnits = currentUnits; currentUnits = (VolumeUnits)(((int)currentUnits + 1) % numUnits); updateUnitsLabel(); if(string.IsNullOrEmpty(volumeField.text) || !float.TryParse(volumeField.text, out var volume)) return; // ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault switch(currentUnits) { case VolumeUnits.CUBIC_METERS when oldUnits == VolumeUnits.PARTS: setVolume(volume / 100); break; case VolumeUnits.PARTS when oldUnits == VolumeUnits.CUBIC_METERS: setVolume(volumeToParts(volume)); break; } } private void updateUnitsLabel() { unitsLabel.text = unitNames[currentUnits]; } public void UpdateTankTypes() { if(tankManager == null) return; tankTypeDropdown.SetOptionsSafe(UI_Utils.namesToOptions(tankManager.SupportedTypes)); updateTankTypeDropdownTooltip(tankTypeDropdown.value); } private void updateTankTypeDropdownTooltip(int index) => tankTypeTooltip.SetText(tankManager.GetTypeInfo(tankManager.SupportedTypes[index])); private void setMaxVolume() => setVolume(1, true); private void setHalfVolume() => setVolume(0.5f, true); private void setVolume(float part, bool updateState = false) { var newVolume = currentUnits == VolumeUnits.CUBIC_METERS ? partsToVolume(part) : part * 100; volumeField.SetTextWithoutNotify(newVolume.ToString("R")); if(!updateState) return; if(tankManager.AvailableVolume > 0) volumeOk(tankManager.OnVolumeChanged(tankType, currentUnits == VolumeUnits.CUBIC_METERS ? newVolume : partsToVolume(part))); else volumeNotOk("No free space left"); } private void volumeNotOk(string error) { volumeFieldColorizer.SetColor(Colors.Danger); volumeFieldTooltip.SetText(error); addButton.SetInteractable(false); } private void volumeOk(string tooltip = null) { volumeFieldColorizer.SetColor(Colors.Neutral); volumeFieldTooltip.SetText(tooltip ?? "Volume of the new tank"); addButton.SetInteractable(true); } private void onVolumeChange(string value) { if(!float.TryParse(value, out var newValue)) { volumeNotOk("Entered value is not a number"); return; } if(newValue <= 0) { volumeNotOk("Enter positive number"); return; } string info = null; // ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault switch(currentUnits) { case VolumeUnits.CUBIC_METERS: if(newValue > tankManager.AvailableVolume) { volumeNotOk("Entered volume is greater than the available volume"); return; } info = tankManager.OnVolumeChanged(tankType, newValue); break; case VolumeUnits.PARTS: if(newValue > tankManager.AvailableVolumePercent) { volumeNotOk("Entered volume is greater than the available volume"); return; } info = tankManager.OnVolumeChanged(tankType, partsToVolume(newValue / 100)); break; } volumeOk(info); } private void addTank() { if(!float.TryParse(volumeField.text, out var tankVolume)) return; if(currentUnits == VolumeUnits.PARTS) tankVolume = Mathf.Clamp(partsToVolume(tankVolume / 100), 0, tankManager.AvailableVolume); if(!tankManager.AddTank(tankType, tankVolume)) return; volumeField.SetTextWithoutNotify(""); addButton.SetInteractable(false); managerUI.UpdateDisplay(); } } }
using System; using System.Reflection; using Castle.MicroKernel; using System.Collections.Generic; using System.Collections; using System.Web; using Castle.Core; using Castle.Core.Configuration; using Cuyahoga.Core; using Cuyahoga.Core.Domain; using Cuyahoga.Core.Service; using Cuyahoga.Core.Service.SiteStructure; using Cuyahoga.Web.Util; using log4net; namespace Cuyahoga.Web.Components { /// <summary> /// Responsible for loading module assemblies and registering these in the application. /// </summary> public class ModuleLoader { private static ILog log = LogManager.GetLogger(typeof (ModuleLoader)); private IKernel _kernel; private SessionFactoryHelper _sessionFactoryHelper; private IModuleTypeService _moduleServie; //static object for thread synchronisation private static object lockObject = ""; /// <summary> /// Constructor. /// </summary> /// <param name="kernel"></param> /// <param name="sessionFactoryHelper"></param> public ModuleLoader(IKernel kernel, SessionFactoryHelper sessionFactoryHelper, IModuleTypeService moduleService) { this._kernel = kernel; this._sessionFactoryHelper = sessionFactoryHelper; this._moduleServie = moduleService; } /// <summary> /// Get the module instance that is associated with the given section. /// </summary> /// <param name="section"></param> /// <returns></returns> public ModuleBase GetModuleFromSection(Section section) { ModuleBase module = this.GetModuleFromType(section.ModuleType); if (module != null) { module.Section = section; if (HttpContext.Current != null) { module.SectionUrl = UrlHelper.GetUrlFromSection(section); } module.ReadSectionSettings(); } return module; } /// <summary> /// Get the module instance by its type /// </summary> /// <param name="moduleType"></param> public ModuleBase GetModuleFromType(ModuleType moduleType) { string modulekey = string.Concat("module.", moduleType.ClassName); if (this._kernel.HasComponent(modulekey)) { return (ModuleBase)this._kernel[modulekey]; } else { if (log.IsDebugEnabled) { log.DebugFormat("Unable to find module with key '{0}' in the container.", modulekey); } return null; } } /// <summary> /// Checks if the module is represent in IoC Container configuration /// </summary> /// <param name="moduleTypeType"></param> /// <returns></returns> public bool IsModuleActive(ModuleType moduleTypeType) { return this._kernel.HasComponent(string.Concat("module.", moduleTypeType.ClassName)); } /// <summary> /// Activate all modules that have the AutoActivate property set to true /// </summary> public void RegisterActivatedModules() { if (log.IsDebugEnabled) { log.Debug("Entering module loading."); } HttpContext.Current.Application.Lock(); HttpContext.Current.Application["IsModuleLoading"] = true; HttpContext.Current.Application.UnLock(); IList moduleTypes = this._moduleServie.GetAllModuleTypes(); foreach (ModuleType mt in moduleTypes) { if (mt.AutoActivate) { ActivateModule(mt); } } // Let the application know that the modules are loaded. HttpContext.Current.Application.Lock(); HttpContext.Current.Application["ModulesLoaded"] = true; HttpContext.Current.Application["IsModuleLoading"] = false; HttpContext.Current.Application.UnLock(); if (log.IsDebugEnabled) { log.Debug("Finished module loading."); } } public void ActivateModule(ModuleType moduleType) { //only one thread at a time System.Threading.Monitor.Enter(lockObject); string assemblyQualifiedName = moduleType.ClassName + ", " + moduleType.AssemblyName; if (log.IsDebugEnabled) { log.DebugFormat("Loading module {0}.", assemblyQualifiedName); } // First, try to get the CLR module type Type moduleTypeType = Type.GetType(assemblyQualifiedName); if (moduleTypeType == null) { throw new Exception("Could not find module: " + assemblyQualifiedName); } try { // double check, if we should continue if (this._kernel.HasComponent(moduleTypeType)) { // Module is already registered if (log.IsDebugEnabled) { log.DebugFormat("The module with type {0} is already registered in the container.", moduleTypeType.ToString()); } return; } // First, register optional module services that the module might depend on. foreach (ModuleService moduleService in moduleType.ModuleServices) { Type serviceType = Type.GetType(moduleService.ServiceType); Type classType = Type.GetType(moduleService.ClassType); if (log.IsDebugEnabled) { log.DebugFormat("Loading module service {0}, (1).", moduleService.ServiceKey, moduleService.ClassType); } LifestyleType lifestyle = LifestyleType.Singleton; if (moduleService.Lifestyle != null) { try { lifestyle = (LifestyleType)Enum.Parse(typeof(LifestyleType), moduleService.Lifestyle); } catch (ArgumentException ex) { throw new Exception(String.Format("Unable to load module service {0} with invalid lifestyle {1}." , moduleService.ServiceKey, moduleService.Lifestyle), ex); } } this._kernel.AddComponent(moduleService.ServiceKey, serviceType, classType, lifestyle); } //Register the module this._kernel.AddComponent("module." + moduleTypeType.FullName, moduleTypeType); //Configure NHibernate mappings and make sure we haven't already added this assembly to the NHibernate config if (typeof(INHibernateModule).IsAssignableFrom(moduleTypeType) && ((HttpContext.Current.Application[moduleType.AssemblyName]) == null)) { if (log.IsDebugEnabled) { log.DebugFormat("Adding module assembly {0} to the NHibernate mappings.", moduleTypeType.Assembly.ToString()); } this._sessionFactoryHelper.AddAssembly(moduleTypeType.Assembly); //set application variable to remember the configurated assemblies HttpContext.Current.Application.Lock(); HttpContext.Current.Application[moduleType.AssemblyName] = moduleType.AssemblyName; HttpContext.Current.Application.UnLock(); } } finally { System.Threading.Monitor.Exit(lockObject); } }//end method } }
using System; using System.Globalization; using System.Net; using Orleans; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; using Orleans.TestingHost.Utils; using TestExtensions; using Xunit; using Xunit.Abstractions; namespace UnitTests.General { [Collection(TestEnvironmentFixture.DefaultCollection)] public class Identifiertests { private readonly ITestOutputHelper output; private readonly TestEnvironmentFixture environment; private static readonly Random random = new Random(); class A { } class B : A { } public Identifiertests(ITestOutputHelper output, TestEnvironmentFixture fixture) { this.output = output; this.environment = fixture; } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void ID_IsSystem() { GrainId testGrain = Constants.DirectoryServiceId; output.WriteLine("Testing GrainID " + testGrain); Assert.True(testGrain.IsSystemTarget); // System grain ID is not flagged as a system ID GrainId sGrain = (GrainId)SerializationManager.DeepCopy(testGrain); output.WriteLine("Testing GrainID " + sGrain); Assert.True(sGrain.IsSystemTarget); // String round-trip grain ID is not flagged as a system ID Assert.Equal(testGrain, sGrain); // Should be equivalent GrainId object Assert.Same(testGrain, sGrain); // Should be same / intern'ed GrainId object ActivationId testActivation = ActivationId.GetSystemActivation(testGrain, SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 2456), 0)); output.WriteLine("Testing ActivationID " + testActivation); Assert.True(testActivation.IsSystem); // System activation ID is not flagged as a system ID } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void UniqueKeyKeyExtGrainCategoryDisallowsNullKeyExtension() { Assert.Throws<ArgumentNullException>(() => UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: null)); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void UniqueKeyKeyExtGrainCategoryDisallowsEmptyKeyExtension() { Assert.Throws<ArgumentException>(() => UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: "")); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void UniqueKeyKeyExtGrainCategoryDisallowsWhiteSpaceKeyExtension() { Assert.Throws<ArgumentException>(() => UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: " \t\n\r")); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void UniqueKeySerializationShouldReproduceAnIdenticalObject() { { var expected = UniqueKey.NewKey(Guid.NewGuid()); BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter(); writer.Write(expected); BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes()); var actual = reader.ReadUniqueKey(); Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #1). } { var kx = random.Next().ToString(CultureInfo.InvariantCulture); var expected = UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: kx); BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter(); writer.Write(expected); BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes()); var actual = reader.ReadUniqueKey(); Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #2). } { var kx = random.Next().ToString(CultureInfo.InvariantCulture) + new String('*', 400); var expected = UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: kx); BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter(); writer.Write(expected); BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes()); var actual = reader.ReadUniqueKey(); Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #3). } } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void ParsingUniqueKeyStringificationShouldReproduceAnIdenticalObject() { UniqueKey expected1 = UniqueKey.NewKey(Guid.NewGuid()); string str1 = expected1.ToHexString(); UniqueKey actual1 = UniqueKey.Parse(str1); Assert.Equal(expected1, actual1); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 1). string kx3 = "case 3"; UniqueKey expected3 = UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: kx3); string str3 = expected3.ToHexString(); UniqueKey actual3 = UniqueKey.Parse(str3); Assert.Equal(expected3, actual3); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 3). long pk = random.Next(); UniqueKey expected4 = UniqueKey.NewKey(pk); string str4 = expected4.ToHexString(); UniqueKey actual4 = UniqueKey.Parse(str4); Assert.Equal(expected4, actual4); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 4). pk = random.Next(); string kx5 = "case 5"; UniqueKey expected5 = UniqueKey.NewKey(pk, category: UniqueKey.Category.KeyExtGrain, keyExt: kx5); string str5 = expected5.ToHexString(); UniqueKey actual5 = UniqueKey.Parse(str5); Assert.Equal(expected5, actual5); // UniqueKey.ToString() and UniqueKey.Parse() failed to reproduce an identical object (case 5). } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void GrainIdShouldEncodeAndDecodePrimaryKeyGuidCorrectly() { const int repeat = 100; for (int i = 0; i < repeat; ++i) { Guid expected = Guid.NewGuid(); GrainId grainId = GrainId.GetGrainIdForTesting(expected); Guid actual = grainId.Key.PrimaryKeyToGuid(); Assert.Equal(expected, actual); // Failed to encode and decode grain id } } [Fact, TestCategory("SlowBVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void GrainId_ToFromPrintableString() { Guid guid = Guid.NewGuid(); GrainId grainId = GrainId.GetGrainIdForTesting(guid); GrainId roundTripped = RoundTripGrainIdToParsable(grainId); Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Guid key string extKey = "Guid-ExtKey-1"; guid = Guid.NewGuid(); grainId = GrainId.GetGrainId(0, guid, extKey); roundTripped = RoundTripGrainIdToParsable(grainId); Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Guid key + Extended Key grainId = GrainId.GetGrainId(0, guid, null); roundTripped = RoundTripGrainIdToParsable(grainId); Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Guid key + null Extended Key long key = random.Next(); guid = UniqueKey.NewKey(key).PrimaryKeyToGuid(); grainId = GrainId.GetGrainIdForTesting(guid); roundTripped = RoundTripGrainIdToParsable(grainId); Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Int64 key extKey = "Long-ExtKey-2"; key = random.Next(); guid = UniqueKey.NewKey(key).PrimaryKeyToGuid(); grainId = GrainId.GetGrainId(0, guid, extKey); roundTripped = RoundTripGrainIdToParsable(grainId); Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Int64 key + Extended Key guid = UniqueKey.NewKey(key).PrimaryKeyToGuid(); grainId = GrainId.GetGrainId(0, guid, null); roundTripped = RoundTripGrainIdToParsable(grainId); Assert.Equal(grainId, roundTripped); // GrainId.ToPrintableString -- Int64 key + null Extended Key } private GrainId RoundTripGrainIdToParsable(GrainId input) { string str = input.ToParsableString(); GrainId output = GrainId.FromParsableString(str); return output; } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void UniqueTypeCodeDataShouldStore32BitsOfInformation() { const int expected = unchecked((int)0xfabccbaf); var uk = UniqueKey.NewKey(0, UniqueKey.Category.None, expected); var actual = uk.BaseTypeCode; Assert.Equal(expected, actual); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void UniqueKeysShouldPreserveTheirPrimaryKeyValueIfItIsGuid() { const int all32Bits = unchecked((int)0xffffffff); var expectedKey1 = Guid.NewGuid(); const string expectedKeyExt1 = "1"; var uk1 = UniqueKey.NewKey(expectedKey1, UniqueKey.Category.KeyExtGrain, all32Bits, expectedKeyExt1); string actualKeyExt1; var actualKey1 = uk1.PrimaryKeyToGuid(out actualKeyExt1); Assert.Equal(expectedKey1, actualKey1); //"UniqueKey objects should preserve the value of their primary key (Guid case #1)."); Assert.Equal(expectedKeyExt1, actualKeyExt1); //"UniqueKey objects should preserve the value of their key extension (Guid case #1)."); var expectedKey2 = Guid.NewGuid(); const string expectedKeyExt2 = "2"; var uk2 = UniqueKey.NewKey(expectedKey2, UniqueKey.Category.KeyExtGrain, all32Bits, expectedKeyExt2); string actualKeyExt2; var actualKey2 = uk2.PrimaryKeyToGuid(out actualKeyExt2); Assert.Equal(expectedKey2, actualKey2); // "UniqueKey objects should preserve the value of their primary key (Guid case #2)."); Assert.Equal(expectedKeyExt2, actualKeyExt2); // "UniqueKey objects should preserve the value of their key extension (Guid case #2)."); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void UniqueKeysShouldPreserveTheirPrimaryKeyValueIfItIsLong() { const int all32Bits = unchecked((int)0xffffffff); var n1 = random.Next(); var n2 = random.Next(); const string expectedKeyExt = "1"; var expectedKey = unchecked((long)((((ulong)((uint)n1)) << 32) | ((uint)n2))); var uk = UniqueKey.NewKey(expectedKey, UniqueKey.Category.KeyExtGrain, all32Bits, expectedKeyExt); string actualKeyExt; var actualKey = uk.PrimaryKeyToLong(out actualKeyExt); Assert.Equal(expectedKey, actualKey); // "UniqueKey objects should preserve the value of their primary key (long case)."); Assert.Equal(expectedKeyExt, actualKeyExt); // "UniqueKey objects should preserve the value of their key extension (long case)."); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void ID_HashCorrectness() { // This tests that our optimized Jenkins hash computes the same value as the reference implementation int testCount = 1000; for (int i = 0; i < testCount; i++) { byte[] byteData = new byte[24]; random.NextBytes(byteData); ulong u1 = BitConverter.ToUInt64(byteData, 0); ulong u2 = BitConverter.ToUInt64(byteData, 8); ulong u3 = BitConverter.ToUInt64(byteData, 16); var referenceHash = JenkinsHash.ComputeHash(byteData); var optimizedHash = JenkinsHash.ComputeHash(u1, u2, u3); Assert.Equal(referenceHash, optimizedHash); // "Optimized hash value doesn't match the reference value for inputs {0}, {1}, {2}", u1, u2, u3 } } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void ID_Interning_GrainID() { Guid guid = new Guid(); GrainId gid1 = GrainId.FromParsableString(guid.ToString("B")); GrainId gid2 = GrainId.FromParsableString(guid.ToString("N")); Assert.Equal(gid1, gid2); // Should be equal GrainId's Assert.Same(gid1, gid2); // Should be same / intern'ed GrainId object // Round-trip through Serializer GrainId gid3 = (GrainId)SerializationManager.RoundTripSerializationForTesting(gid1); Assert.Equal(gid1, gid3); // Should be equal GrainId's Assert.Equal(gid2, gid3); // Should be equal GrainId's Assert.Same(gid1, gid3); // Should be same / intern'ed GrainId object Assert.Same(gid2, gid3); // Should be same / intern'ed GrainId object } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void ID_Interning_string_equals() { Interner<string, string> interner = new Interner<string, string>(); const string str = "1"; string r1 = interner.FindOrCreate("1", _ => str); string r2 = interner.FindOrCreate("1", _ => null); // Should always be found Assert.Equal(r1, r2); // 1: Objects should be equal Assert.Same(r1, r2); // 2: Objects should be same / intern'ed // Round-trip through Serializer string r3 = (string)SerializationManager.RoundTripSerializationForTesting(r1); Assert.Equal(r1, r3); // 3: Should be equal Assert.Equal(r2, r3); // 4: Should be equal } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void ID_Intern_FindOrCreate_derived_class() { Interner<int, A> interner = new Interner<int, A>(); var obj1 = new A(); var obj2 = new B(); var obj3 = new B(); var r1 = interner.FindOrCreate(1, _ => obj1); Assert.Equal(obj1, r1); // Objects should be equal Assert.Same(obj1, r1); // Objects should be same / intern'ed var r2 = interner.FindOrCreate(2, _ => obj2); Assert.Equal(obj2, r2); // Objects should be equal Assert.Same(obj2, r2); // Objects should be same / intern'ed // FindOrCreate should not replace instances of same class var r3 = interner.FindOrCreate(2, _ => obj3); Assert.Same(obj2, r3); // FindOrCreate should return previous object Assert.NotSame(obj3, r3); // FindOrCreate should not replace previous object of same class // FindOrCreate should not replace cached instances with instances of most derived class var r4 = interner.FindOrCreate(1, _ => obj2); Assert.Same(obj1, r4); // FindOrCreate return previously cached object Assert.NotSame(obj2, r4); // FindOrCreate should not replace previously cached object // FindOrCreate should not replace cached instances with instances of less derived class var r5 = interner.FindOrCreate(2, _ => obj1); Assert.NotSame(obj1, r5); // FindOrCreate should not replace previously cached object Assert.Same(obj2, r5); // FindOrCreate return previously cached object } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void Interning_SiloAddress() { //string addrStr1 = "1.2.3.4@11111@1"; SiloAddress a1 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345); SiloAddress a2 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345); Assert.Equal(a1, a2); // Should be equal SiloAddress's Assert.Same(a1, a2); // Should be same / intern'ed SiloAddress object // Round-trip through Serializer SiloAddress a3 = (SiloAddress)SerializationManager.RoundTripSerializationForTesting(a1); Assert.Equal(a1, a3); // Should be equal SiloAddress's Assert.Equal(a2, a3); // Should be equal SiloAddress's Assert.Same(a1, a3); // Should be same / intern'ed SiloAddress object Assert.Same(a2, a3); // Should be same / intern'ed SiloAddress object } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void Interning_SiloAddress2() { SiloAddress a1 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345); SiloAddress a2 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 2222), 12345); Assert.NotEqual(a1, a2); // Should not be equal SiloAddress's Assert.NotSame(a1, a2); // Should not be same / intern'ed SiloAddress object } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void Interning_SiloAddress_Serialization() { SiloAddress a1 = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 1111), 12345); // Round-trip through Serializer SiloAddress a3 = (SiloAddress)SerializationManager.RoundTripSerializationForTesting(a1); Assert.Equal(a1, a3); // Should be equal SiloAddress's Assert.Same(a1, a3); // Should be same / intern'ed SiloAddress object } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void GrainID_AsGuid() { string guidString = "0699605f-884d-4343-9977-f40a39ab7b2b"; Guid grainIdGuid = Guid.Parse(guidString); GrainId grainId = GrainId.GetGrainIdForTesting(grainIdGuid); //string grainIdToKeyString = grainId.ToKeyString(); string grainIdToFullString = grainId.ToFullString(); string grainIdToGuidString = GrainIdToGuidString(grainId); string grainIdKeyString = grainId.Key.ToString(); output.WriteLine("Guid={0}", grainIdGuid); output.WriteLine("GrainId={0}", grainId); //output.WriteLine("GrainId.ToKeyString={0}", grainIdToKeyString); output.WriteLine("GrainId.Key.ToString={0}", grainIdKeyString); output.WriteLine("GrainIdToGuidString={0}", grainIdToGuidString); output.WriteLine("GrainId.ToFullString={0}", grainIdToFullString); // Equal: Public APIs //Assert.Equal(guidString, grainIdToKeyString); // GrainId.ToKeyString Assert.Equal(guidString, grainIdToGuidString); // GrainIdToGuidString // Equal: Internal APIs Assert.Equal(grainIdGuid, grainId.GetPrimaryKey()); // GetPrimaryKey Guid // NOT-Equal: Internal APIs Assert.NotEqual(guidString, grainIdKeyString); // GrainId.Key.ToString } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers")] public void SiloAddress_ToFrom_ParsableString() { SiloAddress address1 = SiloAddress.NewLocalAddress(12345); string addressStr1 = address1.ToParsableString(); SiloAddress addressObj1 = SiloAddress.FromParsableString(addressStr1); output.WriteLine("Convert -- From: {0} Got result string: '{1}' object: {2}", address1, addressStr1, addressObj1); Assert.Equal(address1, addressObj1); // SiloAddress equal after To-From-ParsableString //const string addressStr2 = "127.0.0.1-11111-144611139"; const string addressStr2 = "127.0.0.1:11111@144611139"; SiloAddress addressObj2 = SiloAddress.FromParsableString(addressStr2); string addressStr2Out = addressObj2.ToParsableString(); output.WriteLine("Convert -- From: {0} Got result string: '{1}' object: {2}", addressStr2, addressStr2Out, addressObj2); Assert.Equal(addressStr2, addressStr2Out); // SiloAddress equal after From-To-ParsableString } internal string GrainIdToGuidString(GrainId grainId) { const string pkIdentifierStr = "PrimaryKey:"; string grainIdFullString = grainId.ToFullString(); int pkStartIdx = grainIdFullString.IndexOf(pkIdentifierStr, StringComparison.Ordinal) + pkIdentifierStr.Length + 1; string pkGuidString = grainIdFullString.Substring(pkStartIdx, Guid.Empty.ToString().Length); return pkGuidString; } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Identifiers"), TestCategory("GrainReference")] public void GrainReference_Test1() { Guid guid = Guid.NewGuid(); GrainId regularGrainId = GrainId.GetGrainIdForTesting(guid); GrainReference grainRef = GrainReference.FromGrainId(regularGrainId); TestGrainReference(grainRef); grainRef = GrainReference.FromGrainId(regularGrainId, "generic"); TestGrainReference(grainRef); GrainId systemTragetGrainId = GrainId.NewSystemTargetGrainIdByTypeCode(2); grainRef = GrainReference.FromGrainId(systemTragetGrainId, null, SiloAddress.NewLocalAddress(1)); TestGrainReference(grainRef); GrainId observerGrainId = GrainId.NewClientId(); grainRef = GrainReference.NewObserverGrainReference(observerGrainId, GuidId.GetNewGuidId()); TestGrainReference(grainRef); GrainId geoObserverGrainId = GrainId.NewClientId("clusterid"); grainRef = GrainReference.NewObserverGrainReference(geoObserverGrainId, GuidId.GetNewGuidId()); TestGrainReference(grainRef); } private void TestGrainReference(GrainReference grainRef) { GrainReference roundTripped = RoundTripGrainReferenceToKey(grainRef); Assert.Equal(grainRef, roundTripped); // GrainReference.ToKeyString roundTripped = SerializationManager.RoundTripSerializationForTesting(grainRef); Assert.Equal(grainRef, roundTripped); // GrainReference.OrleansSerializer roundTripped = TestingUtils.RoundTripDotNetSerializer(grainRef); Assert.Equal(grainRef, roundTripped); // GrainReference.DotNetSerializer } private GrainReference RoundTripGrainReferenceToKey(GrainReference input) { string str = input.ToKeyString(); GrainReference output = GrainReference.FromKeyString(str); return output; } } }
// 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.Tests { // GetChars(System.Byte[],System.Int32,System.Int32,System.Char[],System.Int32,System.Boolean) public class DecoderGetChars2 { #region Private Fields private const int c_SIZE_OF_ARRAY = 127; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); #endregion #region Positive Test Cases // PosTest1: Call GetChars with ASCII decoder to convert a ASCII byte array [Fact] public void PosTest1() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; char[] expectedChars = new char[bytes.Length]; Decoder decoder = Encoding.UTF8.GetDecoder(); for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)i; } for (int i = 0; i < expectedChars.Length; ++i) { expectedChars[i] = (char)('\0' + i); } VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, true, bytes.Length, expectedChars, "001.1"); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, false, bytes.Length, expectedChars, "001.2"); } // PosTest2: Call GetChars with Unicode decoder to convert a ASCII byte array [Fact] public void PosTest2() { byte[] bytes = new byte[c_SIZE_OF_ARRAY * 2]; char[] chars = new char[c_SIZE_OF_ARRAY]; char[] expectedChars = new char[c_SIZE_OF_ARRAY]; Decoder decoder = Encoding.Unicode.GetDecoder(); byte c = 0; for (int i = 0; i < bytes.Length; i += 2) { bytes[i] = c++; bytes[i + 1] = 0; } for (int i = 0; i < expectedChars.Length; ++i) { expectedChars[i] = (char)('\0' + i); } VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, true, expectedChars.Length, expectedChars, "002.1"); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, false, expectedChars.Length, expectedChars, "002.2"); } // PosTest3: Call GetChars with Unicode decoder to convert a Unicode byte array [Fact] public void PosTest3() { byte[] bytes = new byte[] { 217, 143, 42, 78, 0, 78, 42, 78, 75, 109, 213, 139 }; char[] expected = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray(); char[] chars = new char[expected.Length]; Decoder decoder = Encoding.Unicode.GetDecoder(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, true, expected.Length, expected, "003.1"); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, false, expected.Length, expected, "003.2"); } // PosTest4: Call GetChars with ASCII decoder to convert partial of ASCII byte array [Fact] public void PosTest4() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; Decoder decoder = Encoding.UTF8.GetDecoder(); for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)i; } VerificationHelper(decoder, bytes, 0, bytes.Length / 2, chars, 0, true, bytes.Length / 2, "004.1"); VerificationHelper(decoder, bytes, bytes.Length / 2, bytes.Length / 2, chars, chars.Length / 2, true, bytes.Length / 2, "004.2"); } // PosTest5: Call GetChars with Unicode decoder to convert partial of an Unicode byte array [Fact] public void PosTest5() { byte[] bytes = new byte[] { 217, 143, 42, 78, 0, 78, 42, 78, 75, 109, 213, 139 }; char[] expected = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray(); char[] chars = new char[expected.Length]; Decoder decoder = Encoding.Unicode.GetDecoder(); VerificationHelper(decoder, bytes, 0, bytes.Length / 2, chars, 0, true, chars.Length / 2, "005.1"); VerificationHelper(decoder, bytes, bytes.Length / 2, bytes.Length / 2, chars, 1, true, chars.Length / 2, "005.2"); } // PosTest6: Call GetChars with ASCII decoder to convert arbitrary byte array [Fact] public void PosTest6() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; Decoder decoder = Encoding.UTF8.GetDecoder(); _generator.GetBytes(-55, bytes); decoder.GetChars(bytes, 0, bytes.Length, chars, 0, true); decoder.GetChars(bytes, 0, bytes.Length, chars, 0, false); } // PosTest7: Call GetChars with Unicode decoder to convert arbitrary byte array [Fact] public void PosTest7() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; Decoder decoder = Encoding.Unicode.GetDecoder(); _generator.GetBytes(-55, bytes); decoder.GetChars(bytes, 0, bytes.Length, chars, 0, true); decoder.GetChars(bytes, 0, bytes.Length, chars, 0, false); } // PosTest8: Call GetChars but convert nothing [Fact] public void PosTest8() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; Decoder decoder = Encoding.UTF8.GetDecoder(); _generator.GetBytes(-55, bytes); VerificationHelper(decoder, bytes, 0, 0, chars, 0, true, 0, "008.1"); decoder = Encoding.Unicode.GetDecoder(); VerificationHelper(decoder, bytes, 0, 0, chars, 0, false, 0, "008.2"); } #endregion #region Nagetive Test Cases // NegTest1: ArgumentNullException should be throw when bytes is a null reference or chars is a null reference [Fact] public void NegTest1() { Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentNullException>(decoder, null, 0, 0, chars, 0, true, typeof(ArgumentNullException), "101.1"); VerificationHelper<ArgumentNullException>(decoder, bytes, 0, 0, null, 0, true, typeof(ArgumentNullException), "101.2"); } // NegTest2: ArgumentOutOfRangeException should be throw when byteIndex or byteCount or charIndex is less than zero. [Fact] public void NegTest2() { Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 0, -1, chars, 0, true, typeof(ArgumentOutOfRangeException), "102.1"); VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 0, 0, chars, -1, true, typeof(ArgumentOutOfRangeException), "102.2"); VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, -1, 0, chars, 0, true, typeof(ArgumentOutOfRangeException), "102.3"); } // NegTest3: ArgumentException should be throw when charCount is less than the resulting number of characters [Fact] public void NegTest3() { Decoder decoder = Encoding.UTF8.GetDecoder(); byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[1]; _generator.GetBytes(-55, bytes); VerificationHelper<ArgumentException>(decoder, bytes, 0, bytes.Length, chars, 0, true, typeof(ArgumentException), "103.1"); } // NegTest4: ArgumentOutOfRangeException should be throw when byteindex and byteCount do not denote a valid range in bytes. [Fact] public void NegTest4() { Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 1, bytes.Length, chars, 0, true, typeof(ArgumentOutOfRangeException), "104.1"); VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, bytes.Length, 1, chars, 0, true, typeof(ArgumentOutOfRangeException), "104.2"); } // NegTest5: ArgumentOutOfRangeException should be throw when charIndex is not a valid index in chars. [Fact] public void NegTest5() { Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentOutOfRangeException>(decoder, bytes, 1, 0, chars, chars.Length + 1, true, typeof(ArgumentOutOfRangeException), "105.1"); } #endregion private void VerificationHelper<T>(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush, Type expected, string errorno) where T : Exception { Assert.Throws<T>(() => { decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex, flush); }); } private void VerificationHelper(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush, int expected, string errorno) { int actual = decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex, flush); Assert.Equal(expected, actual); } private void VerificationHelper(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush, int expected, char[] expectedChars, string errorno) { VerificationHelper(decoder, bytes, byteIndex, byteCount, chars, charIndex, flush, expected, errorno + ".1"); Assert.Equal(expectedChars.Length, chars.Length); Assert.Equal(expectedChars, chars); } } }
using System.Threading; using UnityEngine; namespace PlayFab.Sockets { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Connections; using Microsoft.AspNetCore.SignalR.Client; using Models; using Newtonsoft.Json.Linq; public class PlayFabSignalRService { //Delegates for events fired from the service public delegate void OnConnectEvent(); public delegate void OnDisconnectEvent(); public delegate void OnConnectionFailedEvent(PlayFabError error); public bool Debugging { get; set; } //Delegated events that you can subscribe to recieve notification from the service public event OnConnectEvent OnConnect; public event OnDisconnectEvent OnDisconnect; public event OnConnectionFailedEvent OnConnectionError; /// <summary> /// Reference to Hub Connection /// </summary> private HubConnection _hubConnection = null; /// <summary> /// Access Token for making requests to Relay /// </summary> private string _accessToken = ""; /// <summary> /// Url for making requests to Relay /// </summary> private string _uri = ""; /// <summary> /// Dictionary of topic handlers the Client is subscribed /// </summary> private static readonly ConcurrentDictionary<Topic, ConcurrentBag<Action<PlayFabNetworkMessage>>> UserTopicHandlers = new ConcurrentDictionary<Topic, ConcurrentBag<Action<PlayFabNetworkMessage>>>(); /// <summary> /// Connect to the PlayFab to get connection info /// </summary> public void Connect() { if (!PlayFabClientAPI.IsClientLoggedIn()) { //Invoke Authentication error if we are not logged in and stop processing. OnConnectionError?.Invoke(new PlayFabError() { Error = PlayFabErrorCode.NotAuthenticated, ErrorMessage = "Developer must authenticate with a PlayFabClientAPI Login before calling Connect on the Service." }); return; } //Reach out to PlayFab endpoint and get the connection info Internal.PlayFabHttp.MakeApiCall<GetConnectionInfoResponse>(Endpoints.GetConnectionInfo, new GetConnectionInfoRequest(), Internal.AuthType.EntityToken, OnConnectionInfoSuccess, OnConnectionInfoFailure); } /// <summary> /// Disconnect from the hub, this removes all subscriptions server side /// </summary> public void Disconnect() { InternalDisconnect(); } /// <summary> /// This async method actually does the disconnection work /// </summary> private async void InternalDisconnect() { if (_hubConnection != null) { await _hubConnection.StopAsync(); } OnDisconnect?.Invoke(); } /// <summary> /// Handles connection info response from PlayFab (called on Connect) and starts the connection to the hub. /// </summary> /// <param name="connectionInfo"></param> private async void OnConnectionInfoSuccess(GetConnectionInfoResponse connectionInfo) { _accessToken = connectionInfo.AccessToken; _uri = connectionInfo.Url; CreateHubConnection(); try { if (Debugging) { Debug.Log("Trying to connect to hub"); } await _hubConnection.StartAsync(); if (Debugging) { Debug.Log("Connected To Hub"); } OnConnect?.Invoke(); } catch (Exception ex) { OnConnectionError?.Invoke(new PlayFabError() { Error = PlayFabErrorCode.InternalServerError, ErrorMessage = string.Format("PersistentSocket failed to start the connection with the message: {0}", !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty) }); } } /// <summary> /// Handler for if we could not connect to a PlayFab title and get SignalR Hub connection info /// </summary> /// <param name="error"></param> private void OnConnectionInfoFailure(PlayFabError error) { OnConnectionError?.Invoke(error); } /// <summary> /// Subscribe to a PlayStream or Message topic /// </summary> /// <param name="topic">The topic you wish to subscribe to</param> /// <param name="subscribeComplete">Fires if subscription was successful</param> /// <param name="exceptionCallback">Fires if the subscription was unsuccessful</param> public void Subscribe(Topic topic, Action subscribeComplete, Action<Exception> exceptionCallback, Action<PubSubServiceException> subscribeFailedCallback = null) { InternalSubscribe(topic, subscribeComplete, exceptionCallback, subscribeFailedCallback); } /// <summary> /// Subscribe to multiple PlayStream or Message topics at once /// </summary> /// <param name="topics">A list of topics you wish to subscribe to</param> /// <param name="subscribeComplete">Fires upon success, returns a List of topics that were successfully subscribed to. pass null to omit event</param> /// <param name="exceptionCallback">Fires upon failure to subscribe, returns a list of Exceptions from failed subscriptions. pass null to omit event</param> public void Subscribe(List<Topic> topics, Action<List<Topic>> subscribeComplete, Action<List<Exception>> exceptionCallback) { var taskList = new Task(() => { var listOfExceptions = new List<Exception>(); var listOfTopicsSuccess = new List<Topic>(); var topicCount = topics.Count; var topicProgress = 0; topics.ForEach((topic) => { var t = topic; Subscribe(t, () => { listOfTopicsSuccess.Add(t); topicProgress++; if (Debugging) { Debug.LogFormat("Topic: {0} added", t.FullName); } }, (error) => { listOfExceptions.Add(error); topicProgress++; }); }); while (topicProgress < topicCount) { Thread.Sleep(1); } if (listOfTopicsSuccess.Count > 0) { subscribeComplete?.Invoke(listOfTopicsSuccess); } if (listOfExceptions.Count > 0) { exceptionCallback?.Invoke(listOfExceptions); } }); taskList.Start(); } /// <summary> /// Internal method to perform the subscription aysc /// </summary> /// <param name="topic"></param> /// <param name="subscribeComplete"></param> /// <param name="exceptionCallback"></param> private async void InternalSubscribe(Topic topic, Action subscribeComplete, Action<Exception> exceptionCallback, Action<PubSubServiceException> subscribeExceptionCallback) { try { var pubSubResponse = await _hubConnection.InvokeAsync<PubSubResponse>("Subscribe", new SubscribeRequest { Topic = topic }); if (pubSubResponse.code != 200) { PubSubJsonError errorResponse = ((JObject)pubSubResponse.content).ToObject<PubSubJsonError>(); subscribeExceptionCallback?.Invoke(new PubSubServiceException(errorResponse.error, errorResponse.errorDetails["requestId"])); } else { subscribeComplete?.Invoke(); } } catch (Exception ex) { exceptionCallback?.Invoke(ex); } } /// <summary> /// Unsubscribe from a topic /// </summary> /// <param name="topic">The topic you wish to unsubscribe from</param> /// <param name="unsubscribeComplete">Fires if unsubscription was successful, pass null to omit event</param> /// <param name="exceptionCallback">Fires if unsubscription was not successful, pass null to omit event</param> public void Unsubscribe(Topic topic, Action unsubscribeComplete, Action<Exception> exceptionCallback, Action<PubSubServiceException> unsubscribeExceptionCallback = null) { InternalUnsubscribe(topic, unsubscribeComplete, exceptionCallback, unsubscribeExceptionCallback); } /// <summary> /// Unsubscribe from multiple topics at onces /// </summary> /// <param name="topics">List of topics to unsubscribe from</param> /// <param name="unsubscribeComplete">List of topics you successfully unsubscribed from. pass null to omit event</param> /// <param name="exceptionCallback">List of exceptions from failed unsubscriptions. pass null to omit event</param> public void Unsubscribe(List<Topic> topics, Action<List<Topic>> unsubscribeComplete, Action<List<Exception>> exceptionCallback) { var taskList = new Task(() => { var listOfExceptions = new List<Exception>(); var listOfTopicsSuccess = new List<Topic>(); var topicCount = topics.Count; var topicProgress = 0; topics.ForEach((topic) => { var t = topic; Unsubscribe(t, () => { listOfTopicsSuccess.Add(t); }, (error) => { listOfExceptions.Add(error); }); }); while (topicProgress < topicCount) { Thread.Sleep(1); } if (listOfTopicsSuccess.Count > 0) { unsubscribeComplete?.Invoke(listOfTopicsSuccess); } if (listOfExceptions.Count > 0) { exceptionCallback?.Invoke(listOfExceptions); } }); taskList.Start(); } /// <summary> /// Internal method to perform the unsubscription asyc /// </summary> /// <param name="topic"></param> /// <param name="unsubscribeComplete"></param> /// <param name="exceptionCallback"></param> private async void InternalUnsubscribe(Topic topic, Action unsubscribeComplete, Action<Exception> exceptionCallback, Action<PubSubServiceException> unsubscribeExceptionCallback) { try { var pubSubResponse = await _hubConnection.InvokeAsync<PubSubResponse>("Unsubscribe", new UnsubscribeRequest { Topic = topic }); if (pubSubResponse.code != 200) { PubSubJsonError errorResponse = ((JObject)pubSubResponse.content).ToObject<PubSubJsonError>(); unsubscribeExceptionCallback?.Invoke(new PubSubServiceException(errorResponse.error, errorResponse.errorDetails["requestId"])); } else { unsubscribeComplete?.Invoke(); } } catch (Exception ex) { exceptionCallback?.Invoke(ex); } } /// <summary> /// Register a handler to receive messages on a topic /// </summary> /// <param name="topic">Topic you wish to receive a message about</param> /// <param name="handler">Function (Action) handler that can receive the message</param> public void RegisterHandler(Topic topic, Action<PlayFabNetworkMessage> handler) { if (UserTopicHandlers.ContainsKey(topic)) { // only allow unique handlers, we don't want to double call the same function if (!UserTopicHandlers[topic].Contains(handler)) { UserTopicHandlers[topic].Add(handler); } } else { UserTopicHandlers.TryAdd(topic, new ConcurrentBag<Action<PlayFabNetworkMessage>>() { handler }); } } /// <summary> /// Unregister a handler from receiving messages on a topic /// </summary> /// <param name="topic">Topic you no longer wish to handle messages for</param> /// <param name="handler">Original handler that you previously registered to handle the message</param> public void UnregisterHandler(Topic topic, Action<PlayFabNetworkMessage> handler) { if (!UserTopicHandlers.ContainsKey(topic)) return; var hasMultipleHandlers = UserTopicHandlers[topic].Count > 1; if (hasMultipleHandlers) { var remainingHandlers = new ConcurrentBag<Action<PlayFabNetworkMessage>>(); foreach (var handle in UserTopicHandlers[topic]) { if (handle != handler) { remainingHandlers.Add(handle); } } UserTopicHandlers.TryAdd(topic, remainingHandlers); } else { ConcurrentBag<Action<PlayFabNetworkMessage>> outBag; UserTopicHandlers.TryRemove(topic, out outBag); } } /// <summary> /// Create the action Hub connection and listen for messages received /// </summary> private void CreateHubConnection() { try { //Note: removed error trapping on setting strings (_uri & _accessToken) because they are guaranteed to be there. _hubConnection = new HubConnectionBuilder() .WithUrl(_uri, options => { options.Transports = HttpTransportType.WebSockets; options.AccessTokenProvider = () => Task.FromResult(_accessToken); }).Build(); var closedTcs = new TaskCompletionSource<object>(); _hubConnection.Closed += e => { if (Debugging) { UnityEngine.Debug.Log($"Connection closed: {e}"); } closedTcs.SetResult(null); return Task.CompletedTask; }; _hubConnection.On<PlayFabNetworkMessage>("ReceiveEvent", InternalOnReceiveMessage); if (Debugging) { UnityEngine.Debug.Log("Hub Created! This should only happen once"); } } catch (Exception ex) { OnConnectionError?.Invoke(new PlayFabError() { Error = PlayFabErrorCode.InternalServerError, ErrorMessage = string.Format("PersistentSocket failed to start the connection with the message: {0}", !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty) }); } } /// <summary> /// Internally Handle messages received and forward them to the Registered Handlers /// </summary> /// <param name="netMsgString"></param> private void InternalOnReceiveMessage(PlayFabNetworkMessage netMsg) { if(UserTopicHandlers.Keys.ToList().Find(k=>k.Equals(netMsg.@event.GetTopic())) == null) return; foreach (var action in UserTopicHandlers[netMsg.@event.GetTopic()]) { action?.Invoke(netMsg); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** ** Purpose: Create a stream over unmanaged memory, mostly ** useful for memory-mapped files. ** ** ===========================================================*/ using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using System.Diagnostics.Contracts; using System.Threading.Tasks; namespace System.IO { /* * This class is used to access a contiguous block of memory, likely outside * the GC heap (or pinned in place in the GC heap, but a MemoryStream may * make more sense in those cases). It's great if you have a pointer and * a length for a section of memory mapped in by someone else and you don't * want to copy this into the GC heap. UnmanagedMemoryStream assumes these * two things: * * 1) All the memory in the specified block is readable or writable, * depending on the values you pass to the constructor. * 2) The lifetime of the block of memory is at least as long as the lifetime * of the UnmanagedMemoryStream. * 3) You clean up the memory when appropriate. The UnmanagedMemoryStream * currently will do NOTHING to free this memory. * 4) All calls to Write and WriteByte may not be threadsafe currently. * * It may become necessary to add in some sort of * DeallocationMode enum, specifying whether we unmap a section of memory, * call free, run a user-provided delegate to free the memory, etc etc. * We'll suggest user write a subclass of UnmanagedMemoryStream that uses * a SafeHandle subclass to hold onto the memory. * Check for problems when using this in the negative parts of a * process's address space. We may need to use unsigned longs internally * and change the overflow detection logic. * * -----SECURITY MODEL AND SILVERLIGHT----- * A few key notes about exposing UMS in silverlight: * 1. No ctors are exposed to transparent code. This version of UMS only * supports byte* (not SafeBuffer). Therefore, framework code can create * a UMS and hand it to transparent code. Transparent code can use most * operations on a UMS, but not operations that directly expose a * pointer. * * 2. Scope of "unsafe" and non-CLS compliant operations reduced: The * Whidbey version of this class has CLSCompliant(false) at the class * level and unsafe modifiers at the method level. These were reduced to * only where the unsafe operation is performed -- i.e. immediately * around the pointer manipulation. Note that this brings UMS in line * with recent changes in pu/clr to support SafeBuffer. * * 3. Currently, the only caller that creates a UMS is ResourceManager, * which creates read-only UMSs, and therefore operations that can * change the length will throw because write isn't supported. A * conservative option would be to formalize the concept that _only_ * read-only UMSs can be creates, and enforce this by making WriteX and * SetLength SecurityCritical. However, this is a violation of * security inheritance rules, so we must keep these safe. The * following notes make this acceptable for future use. * a. a race condition in WriteX that could have allowed a thread to * read from unzeroed memory was fixed * b. memory region cannot be expanded beyond _capacity; in other * words, a UMS creator is saying a writeable UMS is safe to * write to anywhere in the memory range up to _capacity, specified * in the ctor. Even if the caller doesn't specify a capacity, then * length is used as the capacity. */ public class UnmanagedMemoryStream : Stream { private const long UnmanagedMemStreamMaxLength = Int64.MaxValue; [System.Security.SecurityCritical] // auto-generated private SafeBuffer _buffer; [SecurityCritical] private unsafe byte* _mem; private long _length; private long _capacity; private long _position; private long _offset; private FileAccess _access; internal bool _isOpen; [NonSerialized] private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync // Needed for subclasses that need to map a file, etc. [System.Security.SecuritySafeCritical] // auto-generated protected UnmanagedMemoryStream() { unsafe { _mem = null; } _isOpen = false; } [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) { Initialize(buffer, offset, length, FileAccess.Read, false); } [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } // We must create one of these without doing a security check. This // class is created while security is trying to start up. Plus, doing // a Demand from Assembly.GetManifestResourceStream isn't useful. [System.Security.SecurityCritical] // auto-generated internal UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) { Initialize(buffer, offset, length, access, skipSecurityCheck); } [System.Security.SecuritySafeCritical] // auto-generated protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } [System.Security.SecurityCritical] // auto-generated internal void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (length < 0) { throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (buffer.ByteLength < (ulong)(offset + length)) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeBufferOffLen")); } if (access < FileAccess.Read || access > FileAccess.ReadWrite) { throw new ArgumentOutOfRangeException("access"); } Contract.EndContractBlock(); if (_isOpen) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice")); } if (!skipSecurityCheck) { #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 } // check for wraparound unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { buffer.AcquirePointer(ref pointer); if ( (pointer + offset + length) < pointer) { throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround")); } } finally { if (pointer != null) { buffer.ReleasePointer(); } } } _offset = offset; _buffer = buffer; _length = length; _capacity = length; _access = access; _isOpen = true; } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length) { Initialize(pointer, length, length, FileAccess.Read, false); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } // We must create one of these without doing a security check. This // class is created while security is trying to start up. Plus, doing // a Demand from Assembly.GetManifestResourceStream isn't useful. [System.Security.SecurityCritical] // auto-generated internal unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) { Initialize(pointer, length, capacity, access, skipSecurityCheck); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } [System.Security.SecurityCritical] // auto-generated internal unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) { if (pointer == null) throw new ArgumentNullException("pointer"); if (length < 0 || capacity < 0) throw new ArgumentOutOfRangeException((length < 0) ? "length" : "capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (length > capacity) throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity")); Contract.EndContractBlock(); // Check for wraparound. if (((byte*) ((long)pointer + capacity)) < pointer) throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround")); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException("access", Environment.GetResourceString("ArgumentOutOfRange_Enum")); if (_isOpen) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice")); if (!skipSecurityCheck) #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 _mem = pointer; _offset = 0; _length = length; _capacity = capacity; _access = access; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen && (_access & FileAccess.Read) != 0; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _isOpen && (_access & FileAccess.Write) != 0; } } [System.Security.SecuritySafeCritical] // auto-generated protected override void Dispose(bool disposing) { _isOpen = false; unsafe { _mem = null; } // Stream allocates WaitHandles for async calls. So for correctness // call base.Dispose(disposing) for better perf, avoiding waiting // for the finalizers to run on those types. base.Dispose(disposing); } public override void Flush() { if (!_isOpen) __Error.StreamIsClosed(); } [HostProtection(ExternalThreading=true)] [ComVisible(false)] public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCancellation(cancellationToken); try { Flush(); return Task.CompletedTask; } catch(Exception ex) { return Task.FromException(ex); } } public override long Length { get { if (!_isOpen) __Error.StreamIsClosed(); return Interlocked.Read(ref _length); } } public long Capacity { get { if (!_isOpen) __Error.StreamIsClosed(); return _capacity; } } public override long Position { get { if (!CanSeek) __Error.StreamIsClosed(); Contract.EndContractBlock(); return Interlocked.Read(ref _position); } [System.Security.SecuritySafeCritical] // auto-generated set { if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); if (!CanSeek) __Error.StreamIsClosed(); #if WIN32 unsafe { // On 32 bit machines, ensure we don't wrap around. if (value > (long) Int32.MaxValue || _mem + value < _mem) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } #endif Interlocked.Exchange(ref _position, value); } } [CLSCompliant(false)] public unsafe byte* PositionPointer { [System.Security.SecurityCritical] // auto-generated_required get { if (_buffer != null) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); } // Use a temp to avoid a race long pos = Interlocked.Read(ref _position); if (pos > _capacity) throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_UMSPosition")); byte * ptr = _mem + pos; if (!_isOpen) __Error.StreamIsClosed(); return ptr; } [System.Security.SecurityCritical] // auto-generated_required set { if (_buffer != null) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); if (!_isOpen) __Error.StreamIsClosed(); // Note: subtracting pointers returns an Int64. Working around // to avoid hitting compiler warning CS0652 on this line. if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength")); if (value < _mem) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, value - _mem); } } internal unsafe byte* Pointer { [System.Security.SecurityCritical] // auto-generated get { if (_buffer != null) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); return _mem; } } [System.Security.SecuritySafeCritical] // auto-generated public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync if (!_isOpen) __Error.StreamIsClosed(); if (!CanRead) __Error.ReadNotSupported(); // Use a local variable to avoid a race where another thread // changes our position after we decide we can read some bytes. long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); long n = len - pos; if (n > count) n = count; if (n <= 0) return 0; int nInt = (int) n; // Safe because n <= count, which is an Int32 if (nInt < 0) nInt = 0; // _position could be beyond EOF Contract.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1. if (_buffer != null) { unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); Buffer.Memcpy(buffer, offset, pointer + pos + _offset, 0, nInt); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { Buffer.Memcpy(buffer, offset, _mem + pos, 0, nInt); } } Interlocked.Exchange(ref _position, pos + n); return nInt; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // contract validation copied from Read(...) if (cancellationToken.IsCancellationRequested) return Task.FromCancellation<Int32>(cancellationToken); try { Int32 n = Read(buffer, offset, count); Task<Int32> t = _lastReadTask; return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n)); } catch (Exception ex) { Contract.Assert(! (ex is OperationCanceledException)); return Task.FromException<Int32>(ex); } } [System.Security.SecuritySafeCritical] // auto-generated public override int ReadByte() { if (!_isOpen) __Error.StreamIsClosed(); if (!CanRead) __Error.ReadNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); if (pos >= len) return -1; Interlocked.Exchange(ref _position, pos + 1); int result; if (_buffer != null) { unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); result = *(pointer + pos + _offset); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { result = _mem[pos]; } } return result; } public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) __Error.StreamIsClosed(); if (offset > UnmanagedMemStreamMaxLength) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength")); switch(loc) { case SeekOrigin.Begin: if (offset < 0) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, offset); break; case SeekOrigin.Current: long pos = Interlocked.Read(ref _position); if (offset + pos < 0) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, offset + pos); break; case SeekOrigin.End: long len = Interlocked.Read(ref _length); if (len + offset < 0) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, len + offset); break; default: throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin")); } long finalPos = Interlocked.Read(ref _position); Contract.Assert(finalPos >= 0, "_position >= 0"); return finalPos; } [System.Security.SecuritySafeCritical] // auto-generated public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); if (_buffer != null) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); if (!_isOpen) __Error.StreamIsClosed(); if (!CanWrite) __Error.WriteNotSupported(); if (value > _capacity) throw new IOException(Environment.GetResourceString("IO.IO_FixedCapacity")); long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); if (value > len) { unsafe { Buffer.ZeroMemory(_mem+len, value-len); } } Interlocked.Exchange(ref _length, value); if (pos > value) { Interlocked.Exchange(ref _position, value); } } [System.Security.SecuritySafeCritical] // auto-generated public override void Write(byte[] buffer, int offset, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..) if (!_isOpen) __Error.StreamIsClosed(); if (!CanWrite) __Error.WriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + count; // Check for overflow if (n < 0) throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); if (n > _capacity) { throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity")); } if (_buffer == null) { // Check to see whether we are now expanding the stream and must // zero any memory in the middle. if (pos > len) { unsafe { Buffer.ZeroMemory(_mem+len, pos-len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory if (n > len) { Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { long bytesLeft = _capacity - pos; if (bytesLeft < count) { throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall")); } unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); Buffer.Memcpy(pointer + pos + _offset, 0, buffer, offset, count); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { Buffer.Memcpy(_mem + pos, 0, buffer, offset, count); } } Interlocked.Exchange(ref _position, n); return; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // contract validation copied from Write(..) if (cancellationToken.IsCancellationRequested) return Task.FromCancellation(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (Exception ex) { Contract.Assert(! (ex is OperationCanceledException)); return Task.FromException<Int32>(ex); } } [System.Security.SecuritySafeCritical] // auto-generated public override void WriteByte(byte value) { if (!_isOpen) __Error.StreamIsClosed(); if (!CanWrite) __Error.WriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + 1; if (pos >= len) { // Check for overflow if (n < 0) throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); if (n > _capacity) throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity")); // Check to see whether we are now expanding the stream and must // zero any memory in the middle. // don't do if created from SafeBuffer if (_buffer == null) { if (pos > len) { unsafe { Buffer.ZeroMemory(_mem+len, pos-len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); *(pointer + pos + _offset) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { _mem[pos] = value; } } Interlocked.Exchange(ref _position, n); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.RecommendationEngine.V1Beta1.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedPredictionServiceClientSnippets { /// <summary>Snippet for Predict</summary> public void PredictRequestObject() { // Snippet: Predict(PredictRequest, CallSettings) // Create client PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create(); // Initialize request argument(s) PredictRequest request = new PredictRequest { PlacementName = PlacementName.FromProjectLocationCatalogEventStorePlacement("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PLACEMENT]"), UserEvent = new UserEvent(), Filter = "", DryRun = false, Params = { { "", new Value() }, }, Labels = { { "", "" }, }, }; // Make the request PagedEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> response = predictionServiceClient.Predict(request); // Iterate over all response items, lazily performing RPCs as required foreach (PredictResponse.Types.PredictionResult item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (PredictResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PredictResponse.Types.PredictionResult item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PredictResponse.Types.PredictionResult> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PredictResponse.Types.PredictionResult item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for PredictAsync</summary> public async Task PredictRequestObjectAsync() { // Snippet: PredictAsync(PredictRequest, CallSettings) // Create client PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync(); // Initialize request argument(s) PredictRequest request = new PredictRequest { PlacementName = PlacementName.FromProjectLocationCatalogEventStorePlacement("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PLACEMENT]"), UserEvent = new UserEvent(), Filter = "", DryRun = false, Params = { { "", new Value() }, }, Labels = { { "", "" }, }, }; // Make the request PagedAsyncEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> response = predictionServiceClient.PredictAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((PredictResponse.Types.PredictionResult item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((PredictResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PredictResponse.Types.PredictionResult item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PredictResponse.Types.PredictionResult> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PredictResponse.Types.PredictionResult item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Predict</summary> public void Predict() { // Snippet: Predict(string, UserEvent, string, int?, CallSettings) // Create client PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]/placements/[PLACEMENT]"; UserEvent userEvent = new UserEvent(); // Make the request PagedEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> response = predictionServiceClient.Predict(name, userEvent); // Iterate over all response items, lazily performing RPCs as required foreach (PredictResponse.Types.PredictionResult item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (PredictResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PredictResponse.Types.PredictionResult item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PredictResponse.Types.PredictionResult> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PredictResponse.Types.PredictionResult item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for PredictAsync</summary> public async Task PredictAsync() { // Snippet: PredictAsync(string, UserEvent, string, int?, CallSettings) // Create client PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]/placements/[PLACEMENT]"; UserEvent userEvent = new UserEvent(); // Make the request PagedAsyncEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> response = predictionServiceClient.PredictAsync(name, userEvent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((PredictResponse.Types.PredictionResult item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((PredictResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PredictResponse.Types.PredictionResult item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PredictResponse.Types.PredictionResult> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PredictResponse.Types.PredictionResult item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Predict</summary> public void PredictResourceNames() { // Snippet: Predict(PlacementName, UserEvent, string, int?, CallSettings) // Create client PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create(); // Initialize request argument(s) PlacementName name = PlacementName.FromProjectLocationCatalogEventStorePlacement("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PLACEMENT]"); UserEvent userEvent = new UserEvent(); // Make the request PagedEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> response = predictionServiceClient.Predict(name, userEvent); // Iterate over all response items, lazily performing RPCs as required foreach (PredictResponse.Types.PredictionResult item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (PredictResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PredictResponse.Types.PredictionResult item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PredictResponse.Types.PredictionResult> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PredictResponse.Types.PredictionResult item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for PredictAsync</summary> public async Task PredictResourceNamesAsync() { // Snippet: PredictAsync(PlacementName, UserEvent, string, int?, CallSettings) // Create client PredictionServiceClient predictionServiceClient = await PredictionServiceClient.CreateAsync(); // Initialize request argument(s) PlacementName name = PlacementName.FromProjectLocationCatalogEventStorePlacement("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]", "[PLACEMENT]"); UserEvent userEvent = new UserEvent(); // Make the request PagedAsyncEnumerable<PredictResponse, PredictResponse.Types.PredictionResult> response = predictionServiceClient.PredictAsync(name, userEvent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((PredictResponse.Types.PredictionResult item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((PredictResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PredictResponse.Types.PredictionResult item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PredictResponse.Types.PredictionResult> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PredictResponse.Types.PredictionResult item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
/* * 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.Physics.Manager; 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; #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_primMesher = RenderingLoader.LoadRenderer(renderers[0]); m_log.DebugFormat("[WARP 3D IMAGE MODULE]: Loaded prim mesher {0}", m_primMesher); } else { m_log.Debug("[WARP 3D IMAGE MODULE]: 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() { // Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f); // Camera above the middle of the region 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 ); // Fill the viewport and return the image return CreateMapTile(viewport, false); } 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) { CreatePrim(renderer, group.RootPart, useTextures); 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; using System.Runtime.Intrinsics; namespace System.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel SSE hardware instructions via intrinsics /// </summary> [CLSCompliant(false)] public abstract class Sse { internal Sse() { } public static bool IsSupported { get { return false; } } public abstract class X64 { internal X64() { } public static bool IsSupported { get { return false; } } /// <summary> /// __int64 _mm_cvtss_si64 (__m128 a) /// CVTSS2SI r64, xmm/m32 /// This intrinisc is only available on 64-bit processes /// </summary> public static long ConvertToInt64(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cvtsi64_ss (__m128 a, __int64 b) /// CVTSI2SS xmm, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static Vector128<float> ConvertScalarToVector128Single(Vector128<float> upper, long value) { throw new PlatformNotSupportedException(); } /// <summary> /// __int64 _mm_cvttss_si64 (__m128 a) /// CVTTSS2SI r64, xmm/m32 /// This intrinisc is only available on 64-bit processes /// </summary> public static long ConvertToInt64WithTruncation(Vector128<float> value) { throw new PlatformNotSupportedException(); } } /// <summary> /// __m128 _mm_add_ps (__m128 a, __m128 b) /// ADDPS xmm, xmm/m128 /// </summary> public static Vector128<float> Add(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_add_ss (__m128 a, __m128 b) /// ADDSS xmm, xmm/m32 /// </summary> public static Vector128<float> AddScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_and_ps (__m128 a, __m128 b) /// ANDPS xmm, xmm/m128 /// </summary> public static Vector128<float> And(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_andnot_ps (__m128 a, __m128 b) /// ANDNPS xmm, xmm/m128 /// </summary> public static Vector128<float> AndNot(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpeq_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(0) /// </summary> public static Vector128<float> CompareEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_comieq_ss (__m128 a, __m128 b) /// COMISS xmm, xmm/m32 /// </summary> public static bool CompareEqualOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_ucomieq_ss (__m128 a, __m128 b) /// UCOMISS xmm, xmm/m32 /// </summary> public static bool CompareEqualUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpeq_ss (__m128 a, __m128 b) /// CMPSS xmm, xmm/m32, imm8(0) /// </summary> public static Vector128<float> CompareEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpgt_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(6) /// </summary> public static Vector128<float> CompareGreaterThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_comigt_ss (__m128 a, __m128 b) /// COMISS xmm, xmm/m32 /// </summary> public static bool CompareGreaterThanOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_ucomigt_ss (__m128 a, __m128 b) /// UCOMISS xmm, xmm/m32 /// </summary> public static bool CompareGreaterThanUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpgt_ss (__m128 a, __m128 b) /// CMPSS xmm, xmm/m32, imm8(6) /// </summary> public static Vector128<float> CompareGreaterThanScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpge_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(5) /// </summary> public static Vector128<float> CompareGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_comige_ss (__m128 a, __m128 b) /// COMISS xmm, xmm/m32 /// </summary> public static bool CompareGreaterThanOrEqualOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_ucomige_ss (__m128 a, __m128 b) /// UCOMISS xmm, xmm/m32 /// </summary> public static bool CompareGreaterThanOrEqualUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpge_ss (__m128 a, __m128 b) /// CMPPS xmm, xmm/m32, imm8(5) /// </summary> public static Vector128<float> CompareGreaterThanOrEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmplt_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(1) /// </summary> public static Vector128<float> CompareLessThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_comilt_ss (__m128 a, __m128 b) /// COMISS xmm, xmm/m32 /// </summary> public static bool CompareLessThanOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_ucomilt_ss (__m128 a, __m128 b) /// UCOMISS xmm, xmm/m32 /// </summary> public static bool CompareLessThanUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmplt_ss (__m128 a, __m128 b) /// CMPSS xmm, xmm/m32, imm8(1) /// </summary> public static Vector128<float> CompareLessThanScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmple_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(2) /// </summary> public static Vector128<float> CompareLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_comile_ss (__m128 a, __m128 b) /// COMISS xmm, xmm/m32 /// </summary> public static bool CompareLessThanOrEqualOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_ucomile_ss (__m128 a, __m128 b) /// UCOMISS xmm, xmm/m32 /// </summary> public static bool CompareLessThanOrEqualUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmple_ss (__m128 a, __m128 b) /// CMPSS xmm, xmm/m32, imm8(2) /// </summary> public static Vector128<float> CompareLessThanOrEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpneq_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(4) /// </summary> public static Vector128<float> CompareNotEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_comineq_ss (__m128 a, __m128 b) /// COMISS xmm, xmm/m32 /// </summary> public static bool CompareNotEqualOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_ucomineq_ss (__m128 a, __m128 b) /// UCOMISS xmm, xmm/m32 /// </summary> public static bool CompareNotEqualUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpneq_ss (__m128 a, __m128 b) /// CMPSS xmm, xmm/m32, imm8(4) /// </summary> public static Vector128<float> CompareNotEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpngt_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(2) /// </summary> public static Vector128<float> CompareNotGreaterThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpngt_ss (__m128 a, __m128 b) /// CMPSS xmm, xmm/m32, imm8(2) /// </summary> public static Vector128<float> CompareNotGreaterThanScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpnge_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(1) /// </summary> public static Vector128<float> CompareNotGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpnge_ss (__m128 a, __m128 b) /// CMPSS xmm, xmm/m32, imm8(1) /// </summary> public static Vector128<float> CompareNotGreaterThanOrEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpnlt_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(5) /// </summary> public static Vector128<float> CompareNotLessThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpnlt_ss (__m128 a, __m128 b) /// CMPSS xmm, xmm/m32, imm8(5) /// </summary> public static Vector128<float> CompareNotLessThanScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpnle_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(6) /// </summary> public static Vector128<float> CompareNotLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpnle_ss (__m128 a, __m128 b) /// CMPSS xmm, xmm/m32, imm8(6) /// </summary> public static Vector128<float> CompareNotLessThanOrEqualScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpord_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(7) /// </summary> public static Vector128<float> CompareOrdered(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpord_ss (__m128 a, __m128 b) /// CMPSS xmm, xmm/m32, imm8(7) /// </summary> public static Vector128<float> CompareOrderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpunord_ps (__m128 a, __m128 b) /// CMPPS xmm, xmm/m128, imm8(3) /// </summary> public static Vector128<float> CompareUnordered(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpunord_ss (__m128 a, __m128 b) /// CMPSS xmm, xmm/m32, imm8(3) /// </summary> public static Vector128<float> CompareUnorderedScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_cvtss_si32 (__m128 a) /// CVTSS2SI r32, xmm/m32 /// </summary> public static int ConvertToInt32(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cvtsi32_ss (__m128 a, int b) /// CVTSI2SS xmm, reg/m32 /// </summary> public static Vector128<float> ConvertScalarToVector128Single(Vector128<float> upper, int value) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_cvttss_si32 (__m128 a) /// CVTTSS2SI r32, xmm/m32 /// </summary> public static int ConvertToInt32WithTruncation(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_div_ps (__m128 a, __m128 b) /// DIVPS xmm, xmm/m128 /// </summary> public static Vector128<float> Divide(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_div_ss (__m128 a, __m128 b) /// DIVSS xmm, xmm/m32 /// </summary> public static Vector128<float> DivideScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_loadu_ps (float const* mem_address) /// MOVUPS xmm, m128 /// </summary> public static unsafe Vector128<float> LoadVector128(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_load_ss (float const* mem_address) /// MOVSS xmm, m32 /// </summary> public static unsafe Vector128<float> LoadScalarVector128(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_load_ps (float const* mem_address) /// MOVAPS xmm, m128 /// </summary> public static unsafe Vector128<float> LoadAlignedVector128(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_loadh_pi (__m128 a, __m64 const* mem_addr) /// MOVHPS xmm, m64 /// </summary> public static unsafe Vector128<float> LoadHigh(Vector128<float> lower, float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_loadl_pi (__m128 a, __m64 const* mem_addr) /// MOVLPS xmm, m64 /// </summary> public static unsafe Vector128<float> LoadLow(Vector128<float> upper, float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_max_ps (__m128 a, __m128 b) /// MAXPS xmm, xmm/m128 /// </summary> public static Vector128<float> Max(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_max_ss (__m128 a, __m128 b) /// MAXSS xmm, xmm/m32 /// </summary> public static Vector128<float> MaxScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_min_ps (__m128 a, __m128 b) /// MINPS xmm, xmm/m128 /// </summary> public static Vector128<float> Min(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_min_ss (__m128 a, __m128 b) /// MINSS xmm, xmm/m32 /// </summary> public static Vector128<float> MinScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_move_ss (__m128 a, __m128 b) /// MOVSS xmm, xmm /// </summary> public static Vector128<float> MoveScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_movehl_ps (__m128 a, __m128 b) /// MOVHLPS xmm, xmm /// </summary> public static Vector128<float> MoveHighToLow(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_movelh_ps (__m128 a, __m128 b) /// MOVLHPS xmm, xmm /// </summary> public static Vector128<float> MoveLowToHigh(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_movemask_ps (__m128 a) /// MOVMSKPS reg, xmm /// </summary> public static int MoveMask(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_mul_ps (__m128 a, __m128 b) /// MULPS xmm, xmm/m128 /// </summary> public static Vector128<float> Multiply(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_mul_ss (__m128 a, __m128 b) /// MULPS xmm, xmm/m32 /// </summary> public static Vector128<float> MultiplyScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_prefetch(char* p, int i) /// PREFETCHT0 m8 /// </summary> public static unsafe void Prefetch0(void* address) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_prefetch(char* p, int i) /// PREFETCHT1 m8 /// </summary> public static unsafe void Prefetch1(void* address) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_prefetch(char* p, int i) /// PREFETCHT2 m8 /// </summary> public static unsafe void Prefetch2(void* address) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_prefetch(char* p, int i) /// PREFETCHNTA m8 /// </summary> public static unsafe void PrefetchNonTemporal(void* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_or_ps (__m128 a, __m128 b) /// ORPS xmm, xmm/m128 /// </summary> public static Vector128<float> Or(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_rcp_ps (__m128 a) /// RCPPS xmm, xmm/m128 /// </summary> public static Vector128<float> Reciprocal(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_rcp_ss (__m128 a) /// RCPSS xmm, xmm/m32 /// </summary> public static Vector128<float> ReciprocalScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_rcp_ss (__m128 a, __m128 b) /// RCPSS xmm, xmm/m32 /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<float> ReciprocalScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_rsqrt_ps (__m128 a) /// RSQRTPS xmm, xmm/m128 /// </summary> public static Vector128<float> ReciprocalSqrt(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_rsqrt_ss (__m128 a) /// RSQRTSS xmm, xmm/m32 /// </summary> public static Vector128<float> ReciprocalSqrtScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_rsqrt_ss (__m128 a, __m128 b) /// RSQRTSS xmm, xmm/m32 /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<float> ReciprocalSqrtScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_shuffle_ps (__m128 a, __m128 b, unsigned int control) /// SHUFPS xmm, xmm/m128, imm8 /// </summary> public static Vector128<float> Shuffle(Vector128<float> left, Vector128<float> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_sqrt_ps (__m128 a) /// SQRTPS xmm, xmm/m128 /// </summary> public static Vector128<float> Sqrt(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_sqrt_ss (__m128 a) /// SQRTSS xmm, xmm/m32 /// </summary> public static Vector128<float> SqrtScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_sqrt_ss (__m128 a, __m128 b) /// SQRTSS xmm, xmm/m32 /// The above native signature does not exist. We provide this additional overload for consistency with the other scalar APIs. /// </summary> public static Vector128<float> SqrtScalar(Vector128<float> upper, Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_store_ps (float* mem_addr, __m128 a) /// MOVAPS m128, xmm /// </summary> public static unsafe void StoreAligned(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_stream_ps (float* mem_addr, __m128 a) /// MOVNTPS m128, xmm /// </summary> public static unsafe void StoreAlignedNonTemporal(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_storeu_ps (float* mem_addr, __m128 a) /// MOVUPS m128, xmm /// </summary> public static unsafe void Store(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_sfence(void) /// SFENCE /// </summary> public static void StoreFence() { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_store_ss (float* mem_addr, __m128 a) /// MOVSS m32, xmm /// </summary> public static unsafe void StoreScalar(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_storeh_pi (__m64* mem_addr, __m128 a) /// MOVHPS m64, xmm /// </summary> public static unsafe void StoreHigh(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_storel_pi (__m64* mem_addr, __m128 a) /// MOVLPS m64, xmm /// </summary> public static unsafe void StoreLow(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_sub_ps (__m128d a, __m128d b) /// SUBPS xmm, xmm/m128 /// </summary> public static Vector128<float> Subtract(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_sub_ss (__m128 a, __m128 b) /// SUBSS xmm, xmm/m32 /// </summary> public static Vector128<float> SubtractScalar(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_unpackhi_ps (__m128 a, __m128 b) /// UNPCKHPS xmm, xmm/m128 /// </summary> public static Vector128<float> UnpackHigh(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_unpacklo_ps (__m128 a, __m128 b) /// UNPCKLPS xmm, xmm/m128 /// </summary> public static Vector128<float> UnpackLow(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_xor_ps (__m128 a, __m128 b) /// XORPS xmm, xmm/m128 /// </summary> public static Vector128<float> Xor(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using NUnit.Framework; namespace Faithlife.Utility.Tests { [TestFixture] public class StringSegmentTests { [Test] public void TestConstructorStringSegmentStr() { var seg = new StringSegment("hey"); Assert.AreEqual(seg.Source, "hey"); Assert.AreEqual(seg.Offset, 0); Assert.AreEqual(seg.Length, 3); } [Test] public void TestConstructorStringSegmentStrNOffset() { var seg = new StringSegment("hey", 1); Assert.AreEqual(seg.Source, "hey"); Assert.AreEqual(seg.Offset, 1); Assert.AreEqual(seg.Length, 2); } [Test] public void TestConstructorStringSegmentStrNOffsetNLength() { var seg = new StringSegment("hey", 1, 1); Assert.AreEqual(seg.Source, "hey"); Assert.AreEqual(seg.Offset, 1); Assert.AreEqual(seg.Length, 1); } [Test] public void TestConstructorStringSegmentDegenerateStart() { var seg = new StringSegment("hey", 0, 0); Assert.AreEqual(seg.Source, "hey"); Assert.AreEqual(seg.Offset, 0); Assert.AreEqual(seg.Length, 0); } [Test] public void TestConstructorStringSegmentDegenerateEnd() { var seg = new StringSegment("hey", 3, 0); Assert.AreEqual(seg.Source, "hey"); Assert.AreEqual(seg.Offset, 3); Assert.AreEqual(seg.Length, 0); } [Test] public void TestConstructorStringSegmentDegenerateMiddle() { var seg = new StringSegment("hey", 1, 0); Assert.AreEqual(seg.Source, "hey"); Assert.AreEqual(seg.Offset, 1); Assert.AreEqual(seg.Length, 0); } [Test] public void TestConstructorNull() { var seg = new StringSegment(null); Assert.AreEqual("", seg.Source); Assert.AreEqual(0, seg.Offset); Assert.AreEqual(0, seg.Length); } [Test] public void TestConstructorStringSegmentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { new StringSegment(null, 1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { new StringSegment(null, 1, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { new StringSegment(null, 1, 1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { new StringSegment("hey", 4, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { new StringSegment("hey", 3, 1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { new StringSegment("hey", 2, 2); }); Assert.Throws<ArgumentOutOfRangeException>(() => { new StringSegment("hey", 1, 3); }); Assert.Throws<ArgumentOutOfRangeException>(() => { new StringSegment("hey", -1, 2); }); Assert.Throws<ArgumentOutOfRangeException>(() => { new StringSegment("hey", 2, -1); }); } [Test] public void TestConstructorStringSegmentStrCapture() { var seg = new StringSegment("hey", Regex.Match("hey", "e")); Assert.AreEqual(seg.Source, "hey"); Assert.AreEqual(seg.Offset, 1); Assert.AreEqual(seg.Length, 1); } [Test] public void TestIndexer() { var seg = new StringSegment("hey!", 1, 2); Assert.Throws<ArgumentOutOfRangeException>(() => { Assert.AreNotEqual(seg[-2], 'h'); }); Assert.Throws<ArgumentOutOfRangeException>(() => { Assert.AreNotEqual(seg[-1], 'h'); }); Assert.AreEqual(seg[0], 'e'); Assert.AreEqual(seg[1], 'y'); Assert.Throws<ArgumentOutOfRangeException>(() => { Assert.AreNotEqual(seg[2], '!'); }); Assert.Throws<ArgumentOutOfRangeException>(() => { Assert.AreNotEqual(seg[3], '!'); }); } [Test] public void TestAfter() { var seg = new StringSegment("hey", 1, 1).After(); Assert.AreEqual(seg.Source, "hey"); Assert.AreEqual(seg.Offset, 2); Assert.AreEqual(seg.Length, 1); } [Test] public void TestAppendToStringBuilder() { var seg = new StringSegment("hey", 1, 1); var sb = new StringBuilder(); seg.AppendToStringBuilder(sb); Assert.AreEqual("e", sb.ToString()); } [Test] public void TestAppendToNullStringBuilder() { var seg = new StringSegment("hey", 1, 1); Assert.Throws<ArgumentNullException>(() => seg.AppendToStringBuilder(null!)); } [Test] public void TestBefore() { var seg = new StringSegment("hey", 1, 1).Before(); Assert.AreEqual(seg.Source, "hey"); Assert.AreEqual(seg.Offset, 0); Assert.AreEqual(seg.Length, 1); } [Test] public void TestCompareSegASegB() { var segA = new StringSegment("Aaa", 0, 2); var segB = new StringSegment("Aaa", 1, 2); Assert.Greater(StringSegment.Compare(segA, segB, StringComparison.InvariantCulture), 0); } [Test] public void TestCompareSegASegBSc() { var segA = new StringSegment("Aaa", 0, 2); var segB = new StringSegment("Aaa", 1, 2); Assert.AreEqual(0, StringSegment.Compare(segA, segB, StringComparison.OrdinalIgnoreCase)); } [Test] public void TestCompareOrdinal() { var segA = new StringSegment("Aaa", 0, 2); var segB = new StringSegment("Aaa", 1, 2); Assert.Less(StringSegment.CompareOrdinal(segA, segB), 0); } [Test] public void TestCompareDifferentLengths() { var segA = new StringSegment("This is a test", 5, 4); var segB = new StringSegment("This is a test", 5, 6); Assert.Less(segA.CompareTo(segB), 0); Assert.Less(StringSegment.Compare(segA, segB, StringComparison.Ordinal), 0); Assert.Less(StringSegment.CompareOrdinal(segA, segB), 0); } [Test] public void TestCompareTo() { var segA = new StringSegment("abc", 0, 2); var segB = new StringSegment("abc", 1, 2); Assert.Less(segA.CompareTo(segB), 0); } [Test] public void TestCopyTo() { var seg = new StringSegment("hey", 1); char[] ach = { 'o', 'x' }; seg.CopyTo(1, ach, 1, 1); CollectionAssert.AreEqual(new char[] { 'o', 'y' }, ach); } [Test] public void TestEqualsSelf() { var segA = new StringSegment("hey", 1); Assert.AreEqual(segA, segA); Assert.AreEqual(segA, segA); } [Test] public void TestEqualsIdentical() { var segA = new StringSegment("hey", 1); var segB = new StringSegment("hey", 1); Assert.AreEqual(segA, segB); Assert.AreEqual(segA, segB); Assert.IsTrue(segA == segB); Assert.IsFalse(segA != segB); } [Test] public void TestEqualsDifferentOffset() { var segA = new StringSegment("hey you", 2, 1); var segB = new StringSegment("hey you", 4, 1); Assert.AreEqual(segA, segB); Assert.AreEqual(segA, segB); Assert.IsTrue(segA == segB); Assert.IsFalse(segA != segB); } [Test] public void TestEqualsDifferentOwner() { var segA = new StringSegment("hey", 2, 1); var segB = new StringSegment("you", 0, 1); Assert.AreEqual(segA, segB); Assert.AreEqual(segA, segB); Assert.IsTrue(segA == segB); Assert.IsFalse(segA != segB); } [Test] public void TestNotEqualsDifferentLength() { var segA = new StringSegment("hey", 1, 1); var segB = new StringSegment("hey", 1, 2); Assert.AreNotEqual(segA, segB); Assert.AreNotEqual(segA, segB); Assert.IsTrue(segA != segB); Assert.IsFalse(segA == segB); } [Test] public void TestNotEqualsDifferentText() { var segA = new StringSegment("hey", 1, 1); var segB = new StringSegment("hey", 2, 1); Assert.AreNotEqual(segA, segB); Assert.AreNotEqual(segA, segB); Assert.IsTrue(segA != segB); Assert.IsFalse(segA == segB); } [Test] public void TestNotEqualsCase() { var segA = new StringSegment("AAA", 1, 1); var segB = new StringSegment("aaa", 2, 1); Assert.AreNotEqual(segA, segB); Assert.AreNotEqual(segA, segB); Assert.IsTrue(segA != segB); Assert.IsFalse(segA == segB); } [Test] public void TestGetEnumerator() { var str = ""; foreach (var ch in new StringSegment("hey", 1)) str += ch; #pragma warning disable CS8605 // Unboxing a possibly null value. foreach (char ch in (IEnumerable) new StringSegment("hey", 1)) #pragma warning restore CS8605 // Unboxing a possibly null value. str += ch; Assert.AreEqual("eyey", str); } [Test] public void TestGetHashCode() { Assert.AreEqual("ey".GetHashCode(), new StringSegment("hey", 1).GetHashCode()); Assert.AreEqual("ey".GetHashCode(), new StringSegment("eye", 0, 2).GetHashCode()); } [Test] public void TestIndexOfCh() { var seg = new StringSegment("hey you", 1, 5); Assert.AreEqual(-1, seg.IndexOf('h')); Assert.AreEqual(0, seg.IndexOf('e')); Assert.AreEqual(1, seg.IndexOf('y')); Assert.AreEqual(-1, seg.IndexOf('u')); Assert.AreEqual(-1, seg.IndexOf('x')); } [Test] public void TestIndexOfCharWithStartOffset() { var seg = new StringSegment("hey you", 1, 5); Assert.AreEqual(-1, seg.IndexOf('h', 0)); Assert.AreEqual(0, seg.IndexOf('e', 0)); Assert.AreEqual(-1, seg.IndexOf('e', 1)); Assert.AreEqual(1, seg.IndexOf('y', 0)); Assert.AreEqual(1, seg.IndexOf('y', 1)); Assert.AreEqual(3, seg.IndexOf('y', 2)); Assert.AreEqual(-1, seg.IndexOf('y', 4)); Assert.AreEqual(-1, seg.IndexOf('u', 0)); Assert.AreEqual(-1, seg.IndexOf('x', 0)); Assert.Throws<ArgumentOutOfRangeException>(() => seg.IndexOf('h', -1)); Assert.Throws<ArgumentOutOfRangeException>(() => seg.IndexOf('u', 5)); } [Test] public void TestIndexOfStr() { var seg = new StringSegment("hey you", 1, 5); Assert.AreEqual(-1, seg.IndexOf("he", StringComparison.Ordinal)); Assert.AreEqual(0, seg.IndexOf("ey", StringComparison.Ordinal)); Assert.AreEqual(1, seg.IndexOf("y", StringComparison.Ordinal)); Assert.AreEqual(-1, seg.IndexOf("ou", StringComparison.Ordinal)); Assert.AreEqual(-1, seg.IndexOf("ox", StringComparison.Ordinal)); } [Test] public void TestIndexOfAny() { var seg = new StringSegment("hey you", 1, 5); Assert.AreEqual(-1, seg.IndexOfAny(new char[] { 'h' })); Assert.AreEqual(0, seg.IndexOfAny(new char[] { 'h', 'e' })); Assert.AreEqual(1, seg.IndexOfAny('h', 'y', 'x')); Assert.AreEqual(-1, seg.IndexOfAny(new char[] { 'u', 'v' })); Assert.AreEqual(-1, seg.IndexOfAny(new char[] { 'h' })); } [Test] public void TestIntersect() { var str = "01234567"; var segFull = new StringSegment(str); var segFirstHalf = new StringSegment(str, 0, 4); var segLastHalf = new StringSegment(str, 4); var segMiddle = new StringSegment(str, 2, 4); var segSecondChar = new StringSegment(str, 1, 1); var segLastChar = new StringSegment(str, 7, 1); var segCenter = new StringSegment(str, 4, 0); Assert.IsTrue(segFull.Intersect(segFull).IsIdenticalTo(segFull)); Assert.IsTrue(segFull.Intersect(segFirstHalf).IsIdenticalTo(segFirstHalf)); Assert.IsTrue(segFull.Intersect(segLastHalf).IsIdenticalTo(segLastHalf)); Assert.IsTrue(segFull.Intersect(segMiddle).IsIdenticalTo(segMiddle)); Assert.IsTrue(segFull.Intersect(segSecondChar).IsIdenticalTo(segSecondChar)); Assert.IsTrue(segFull.Intersect(segLastChar).IsIdenticalTo(segLastChar)); Assert.IsTrue(segFull.Intersect(segCenter).IsIdenticalTo(segCenter)); Assert.IsTrue(segFirstHalf.Intersect(segFull).IsIdenticalTo(segFirstHalf)); Assert.IsTrue(segFirstHalf.Intersect(segFirstHalf).IsIdenticalTo(segFirstHalf)); Assert.IsTrue(segFirstHalf.Intersect(segLastHalf).IsIdenticalTo(segCenter)); Assert.IsTrue(segFirstHalf.Intersect(segMiddle).IsIdenticalTo(new StringSegment(str, 2, 2))); Assert.IsTrue(segFirstHalf.Intersect(segSecondChar).IsIdenticalTo(segSecondChar)); Assert.IsTrue(segFirstHalf.Intersect(segLastChar).IsIdenticalTo(new StringSegment(str, 7, 0))); Assert.IsTrue(segFirstHalf.Intersect(segCenter).IsIdenticalTo(segCenter)); Assert.IsTrue(segLastHalf.Intersect(segFull).IsIdenticalTo(segLastHalf)); Assert.IsTrue(segLastHalf.Intersect(segFirstHalf).IsIdenticalTo(segCenter)); Assert.IsTrue(segLastHalf.Intersect(segLastHalf).IsIdenticalTo(segLastHalf)); Assert.IsTrue(segLastHalf.Intersect(segMiddle).IsIdenticalTo(new StringSegment(str, 4, 2))); Assert.IsTrue(segLastHalf.Intersect(segSecondChar).IsIdenticalTo(segCenter)); Assert.IsTrue(segLastHalf.Intersect(segLastChar).IsIdenticalTo(segLastChar)); Assert.IsTrue(segLastHalf.Intersect(segCenter).IsIdenticalTo(segCenter)); Assert.IsTrue(segMiddle.Intersect(segFull).IsIdenticalTo(segMiddle)); Assert.IsTrue(segMiddle.Intersect(segFirstHalf).IsIdenticalTo(new StringSegment(str, 2, 2))); Assert.IsTrue(segMiddle.Intersect(segLastHalf).IsIdenticalTo(new StringSegment(str, 4, 2))); Assert.IsTrue(segMiddle.Intersect(segMiddle).IsIdenticalTo(segMiddle)); Assert.IsTrue(segMiddle.Intersect(segSecondChar).IsIdenticalTo(new StringSegment(str, 2, 0))); Assert.IsTrue(segMiddle.Intersect(segLastChar).IsIdenticalTo(new StringSegment(str, 7, 0))); Assert.IsTrue(segMiddle.Intersect(segCenter).IsIdenticalTo(segCenter)); Assert.IsTrue(segSecondChar.Intersect(segFull).IsIdenticalTo(segSecondChar)); Assert.IsTrue(segSecondChar.Intersect(segFirstHalf).IsIdenticalTo(segSecondChar)); Assert.IsTrue(segSecondChar.Intersect(segLastHalf).IsIdenticalTo(segCenter)); Assert.IsTrue(segSecondChar.Intersect(segMiddle).IsIdenticalTo(new StringSegment(str, 2, 0))); Assert.IsTrue(segSecondChar.Intersect(segSecondChar).IsIdenticalTo(segSecondChar)); Assert.IsTrue(segSecondChar.Intersect(segLastChar).IsIdenticalTo(new StringSegment(str, 7, 0))); Assert.IsTrue(segSecondChar.Intersect(segCenter).IsIdenticalTo(segCenter)); Assert.IsTrue(segLastChar.Intersect(segFull).IsIdenticalTo(segLastChar)); Assert.IsTrue(segLastChar.Intersect(segFirstHalf).IsIdenticalTo(new StringSegment(str, 7, 0))); Assert.IsTrue(segLastChar.Intersect(segLastHalf).IsIdenticalTo(segLastChar)); Assert.IsTrue(segLastChar.Intersect(segMiddle).IsIdenticalTo(new StringSegment(str, 7, 0))); Assert.IsTrue(segLastChar.Intersect(segSecondChar).IsIdenticalTo(new StringSegment(str, 7, 0))); Assert.IsTrue(segLastChar.Intersect(segLastChar).IsIdenticalTo(segLastChar)); Assert.IsTrue(segLastChar.Intersect(segCenter).IsIdenticalTo(new StringSegment(str, 7, 0))); Assert.IsTrue(segCenter.Intersect(segFull).IsIdenticalTo(segCenter)); Assert.IsTrue(segCenter.Intersect(segFirstHalf).IsIdenticalTo(segCenter)); Assert.IsTrue(segCenter.Intersect(segLastHalf).IsIdenticalTo(segCenter)); Assert.IsTrue(segCenter.Intersect(segMiddle).IsIdenticalTo(segCenter)); Assert.IsTrue(segCenter.Intersect(segSecondChar).IsIdenticalTo(segCenter)); Assert.IsTrue(segCenter.Intersect(segLastChar).IsIdenticalTo(new StringSegment(str, 7, 0))); Assert.IsTrue(segCenter.Intersect(segCenter).IsIdenticalTo(segCenter)); } [Test] public void TestIntersectDifferent() { Assert.Throws<ArgumentException>(() => new StringSegment("hey", 1, 2).Intersect(new StringSegment("eye", 0, 2))); } [Test] public void TestLastIndexOfCh() { var seg = new StringSegment("hey you", 1, 5); Assert.AreEqual(-1, seg.LastIndexOf('h')); Assert.AreEqual(0, seg.LastIndexOf('e')); Assert.AreEqual(3, seg.LastIndexOf('y')); Assert.AreEqual(-1, seg.LastIndexOf('u')); Assert.AreEqual(-1, seg.LastIndexOf('x')); } [Test] public void TestLastIndexOfStr() { var seg = new StringSegment("hey you", 1, 5); Assert.AreEqual(-1, seg.LastIndexOf("he", StringComparison.Ordinal)); Assert.AreEqual(0, seg.LastIndexOf("ey", StringComparison.Ordinal)); Assert.AreEqual(3, seg.LastIndexOf("y", StringComparison.Ordinal)); Assert.AreEqual(-1, seg.LastIndexOf("ou", StringComparison.Ordinal)); Assert.AreEqual(-1, seg.LastIndexOf("ox", StringComparison.Ordinal)); } [Test] public void TestLastIndexOfAny() { var seg = new StringSegment("hey you", 1, 5); Assert.AreEqual(-1, seg.LastIndexOfAny(new char[] { 'h' })); Assert.AreEqual(0, seg.LastIndexOfAny(new char[] { 'h', 'e' })); Assert.AreEqual(3, seg.LastIndexOfAny('h', 'y', 'x')); Assert.AreEqual(-1, seg.LastIndexOfAny(new char[] { 'u', 'v' })); Assert.AreEqual(-1, seg.LastIndexOfAny(new char[] { 'h' })); } [Test] public void TestMatch() { var str = "hey you"; var seg = new StringSegment(str, 1, 5); var regex = new Regex("[bcdfghjklmnpqrstvwxyz]"); Assert.IsTrue(new StringSegment(str, seg.Match(regex)).IsIdenticalTo(new StringSegment(str, 2, 1))); } [Test] public void TestMatchNull() { var str = "hey you"; var seg = new StringSegment(str, 1, 5); Regex? regex = null; Assert.Throws<ArgumentNullException>(() => seg.Match(regex!)); } [Test] public void TestMatchAnchors() { var str = "hey you"; var seg = new StringSegment(str, 4, 2); var regex = new Regex("^yo$"); Assert.IsTrue(seg.Match(regex).Success); } [Test] public void TestRedirect() { var str = "hey you"; var seg = new StringSegment(str, 1, 5); Assert.IsTrue(seg.Redirect(3).IsIdenticalTo(new StringSegment(str, 3))); Assert.IsTrue(seg.Redirect(3, 2).IsIdenticalTo(new StringSegment(str, 3, 2))); Assert.IsTrue(seg.Redirect(Regex.Match(str, "ey")).IsIdenticalTo(new StringSegment(str, 1, 2))); } [Test] public void TestRedirectNull() { var str = "hey you"; var seg = new StringSegment(str, 1, 5); Capture? capture = null; Assert.Throws<ArgumentNullException>(() => seg.Redirect(capture!)); } [Test] public void TestSplitSimple() { var str = "shiny happy people"; var seg = new StringSegment(str); var regex = new Regex(@"\s", RegexOptions.CultureInvariant); var listSplit = new List<StringSegment>(seg.Split(regex)); Assert.AreEqual(3, listSplit.Count); Assert.AreEqual(new StringSegment(str, 0, 5), listSplit[0]); Assert.AreEqual(new StringSegment(str, 6, 5), listSplit[1]); Assert.AreEqual(new StringSegment(str, 12, 6), listSplit[2]); Assert.AreEqual(3, regex.Split(seg.ToString()).Length); } [Test] public void TestSplitSegment() { var str = "shiny happy people"; var seg = new StringSegment(str, 1, 16); var regex = new Regex(@"\s", RegexOptions.CultureInvariant); var listSplit = new List<StringSegment>(seg.Split(regex)); Assert.AreEqual(3, listSplit.Count); Assert.AreEqual(new StringSegment(str, 1, 4), listSplit[0]); Assert.AreEqual(new StringSegment(str, 6, 5), listSplit[1]); Assert.AreEqual(new StringSegment(str, 12, 5), listSplit[2]); Assert.AreEqual(3, regex.Split(seg.ToString()).Length); } [Test] public void TestSplitEdges() { var str = "shiny happy people"; var seg = new StringSegment(str, 5, 7); var regex = new Regex(@"\s", RegexOptions.CultureInvariant); var listSplit = new List<StringSegment>(seg.Split(regex)); Assert.AreEqual(3, listSplit.Count); Assert.AreEqual(new StringSegment(str, 5, 0), listSplit[0]); Assert.AreEqual(new StringSegment(str, 6, 5), listSplit[1]); Assert.AreEqual(new StringSegment(str, 12, 0), listSplit[2]); Assert.AreEqual(3, regex.Split(seg.ToString()).Length); } [Test] public void TestSplitTrivial() { var str = "shiny happy people"; var seg = new StringSegment(str, 6, 5); var regex = new Regex(@"\s", RegexOptions.CultureInvariant); var listSplit = new List<StringSegment>(seg.Split(regex)); Assert.AreEqual(1, listSplit.Count); Assert.AreEqual(new StringSegment(str, 6, 5), listSplit[0]); Assert.AreEqual(1, regex.Split(seg.ToString()).Length); } [Test] public void TestSplitSegmentGroups() { var str = "shiny happy people"; var seg = new StringSegment(str, 1, 16); var regex = new Regex(@"(\s)", RegexOptions.CultureInvariant); var listSplit = new List<StringSegment>(seg.Split(regex)); Assert.AreEqual(5, listSplit.Count); Assert.AreEqual(new StringSegment(str, 1, 4), listSplit[0]); Assert.AreEqual(new StringSegment(str, 5, 1), listSplit[1]); Assert.AreEqual(new StringSegment(str, 6, 5), listSplit[2]); Assert.AreEqual(new StringSegment(str, 11, 1), listSplit[3]); Assert.AreEqual(new StringSegment(str, 12, 5), listSplit[4]); Assert.AreEqual(5, regex.Split(seg.ToString()).Length); } [Test] public void TestSplitSegmentGroupsRightToLeft() { var str = "shiny happy people"; var seg = new StringSegment(str, 1, 16); var regex = new Regex(@"(\s)", RegexOptions.CultureInvariant | RegexOptions.RightToLeft); var listSplit = new List<StringSegment>(seg.Split(regex)); Assert.AreEqual(5, listSplit.Count, "listSplit has incorrect count."); Assert.AreEqual(new StringSegment(str, 1, 4), listSplit[4]); Assert.AreEqual(new StringSegment(str, 5, 1), listSplit[3]); Assert.AreEqual(new StringSegment(str, 6, 5), listSplit[2]); Assert.AreEqual(new StringSegment(str, 11, 1), listSplit[1]); Assert.AreEqual(new StringSegment(str, 12, 5), listSplit[0]); Assert.AreEqual(5, regex.Split(seg.ToString()).Length, "regex.Split() has incorrect length."); } [Test] public void TestSubstringNIndex() { var str = "hey you"; var seg = new StringSegment(str, 1, 5).Substring(1); Assert.IsTrue(seg.IsIdenticalTo(new StringSegment(str, 2, 4))); } [Test] public void TestSubstringNIndexNLength() { var str = "hey you"; var seg = new StringSegment(str, 1, 5).Substring(1, 3); Assert.IsTrue(seg.IsIdenticalTo(new StringSegment(str, 2, 3))); } [Test] public void TestToCharArray() { CollectionAssert.AreEqual("hey".ToCharArray(), new StringSegment("hey").ToCharArray()); CollectionAssert.AreEqual("ey".ToCharArray(), new StringSegment("hey", 1).ToCharArray()); CollectionAssert.AreEqual("e".ToCharArray(), new StringSegment("hey", 1, 1).ToCharArray()); } [Test] public void TestTrim() { var str = "one two\t three"; Assert.AreEqual(new StringSegment(str), new StringSegment(str).Trim()); Assert.AreEqual(new StringSegment(str, 1), new StringSegment(str, 1).Trim()); Assert.AreEqual(new StringSegment(str, 2), new StringSegment(str, 2).Trim()); Assert.AreEqual(new StringSegment(str, 4), new StringSegment(str, 3).Trim()); Assert.AreEqual(new StringSegment(str, 4), new StringSegment(str, 4).Trim()); Assert.AreEqual(new StringSegment(str, 0, 10), new StringSegment(str, 0, 10).Trim()); Assert.AreEqual(new StringSegment(str, 0, 7), new StringSegment(str, 0, 9).Trim()); Assert.AreEqual(new StringSegment(str, 0, 7), new StringSegment(str, 0, 8).Trim()); Assert.AreEqual(new StringSegment(str, 0, 7), new StringSegment(str, 0, 7).Trim()); Assert.AreEqual(new StringSegment(str, 4, 3), new StringSegment(str, 3, 6).Trim()); } [Test] public void TestTrimStart() { var str = "one two\t three"; Assert.AreEqual(new StringSegment(str), new StringSegment(str).TrimStart()); Assert.AreEqual(new StringSegment(str, 1), new StringSegment(str, 1).TrimStart()); Assert.AreEqual(new StringSegment(str, 2), new StringSegment(str, 2).TrimStart()); Assert.AreEqual(new StringSegment(str, 4), new StringSegment(str, 3).TrimStart()); Assert.AreEqual(new StringSegment(str, 4), new StringSegment(str, 4).TrimStart()); Assert.AreEqual(new StringSegment(str, 0, 10), new StringSegment(str, 0, 10).TrimStart()); Assert.AreEqual(new StringSegment(str, 0, 9), new StringSegment(str, 0, 9).TrimStart()); Assert.AreEqual(new StringSegment(str, 0, 8), new StringSegment(str, 0, 8).TrimStart()); Assert.AreEqual(new StringSegment(str, 0, 7), new StringSegment(str, 0, 7).TrimStart()); Assert.AreEqual(new StringSegment(str, 4, 5), new StringSegment(str, 3, 6).TrimStart()); } [Test] public void TestTrimEnd() { var str = "one two\t three"; Assert.AreEqual(new StringSegment(str), new StringSegment(str).TrimEnd()); Assert.AreEqual(new StringSegment(str, 1), new StringSegment(str, 1).TrimEnd()); Assert.AreEqual(new StringSegment(str, 2), new StringSegment(str, 2).TrimEnd()); Assert.AreEqual(new StringSegment(str, 3), new StringSegment(str, 3).TrimEnd()); Assert.AreEqual(new StringSegment(str, 4), new StringSegment(str, 4).TrimEnd()); Assert.AreEqual(new StringSegment(str, 0, 10), new StringSegment(str, 0, 10).TrimEnd()); Assert.AreEqual(new StringSegment(str, 0, 7), new StringSegment(str, 0, 9).TrimEnd()); Assert.AreEqual(new StringSegment(str, 0, 7), new StringSegment(str, 0, 8).TrimEnd()); Assert.AreEqual(new StringSegment(str, 0, 7), new StringSegment(str, 0, 7).TrimEnd()); Assert.AreEqual(new StringSegment(str, 3, 4), new StringSegment(str, 3, 6).TrimEnd()); } [Test] public void TestTrimChar() { var str = "one two\t three"; Assert.AreEqual(new StringSegment(str, 0, 12), new StringSegment(str).Trim('e')); Assert.AreEqual(new StringSegment(str, 1, 11), new StringSegment(str, 1).Trim('e')); Assert.AreEqual(new StringSegment(str, 3, 9), new StringSegment(str, 2).Trim('e')); Assert.AreEqual(new StringSegment(str, 3, 9), new StringSegment(str, 3).Trim('e')); Assert.AreEqual(new StringSegment(str, 4, 8), new StringSegment(str, 4).Trim('e')); Assert.AreEqual(new StringSegment(str, 0, 10), new StringSegment(str, 0, 10).Trim('e')); Assert.AreEqual(new StringSegment(str, 0, 9), new StringSegment(str, 0, 9).Trim('e')); Assert.AreEqual(new StringSegment(str, 0, 8), new StringSegment(str, 0, 8).Trim('e')); Assert.AreEqual(new StringSegment(str, 0, 7), new StringSegment(str, 0, 7).Trim('e')); Assert.AreEqual(new StringSegment(str, 3, 6), new StringSegment(str, 3, 6).Trim('e')); } [Test] public void TestTrimStartChar() { var str = "one two\t three"; Assert.AreEqual(new StringSegment(str), new StringSegment(str).TrimStart('e')); Assert.AreEqual(new StringSegment(str, 1), new StringSegment(str, 1).TrimStart('e')); Assert.AreEqual(new StringSegment(str, 3), new StringSegment(str, 2).TrimStart('e')); Assert.AreEqual(new StringSegment(str, 3), new StringSegment(str, 3).TrimStart('e')); Assert.AreEqual(new StringSegment(str, 4), new StringSegment(str, 4).TrimStart('e')); Assert.AreEqual(new StringSegment(str, 0, 10), new StringSegment(str, 0, 10).TrimStart('e')); Assert.AreEqual(new StringSegment(str, 0, 9), new StringSegment(str, 0, 9).TrimStart('e')); Assert.AreEqual(new StringSegment(str, 0, 8), new StringSegment(str, 0, 8).TrimStart('e')); Assert.AreEqual(new StringSegment(str, 0, 7), new StringSegment(str, 0, 7).TrimStart('e')); Assert.AreEqual(new StringSegment(str, 3, 6), new StringSegment(str, 3, 6).TrimStart('e')); } [Test] public void TestTrimEndChar() { var str = "one two\t three"; Assert.AreEqual(new StringSegment(str, 0, 12), new StringSegment(str).TrimEnd('e')); Assert.AreEqual(new StringSegment(str, 1, 11), new StringSegment(str, 1).TrimEnd('e')); Assert.AreEqual(new StringSegment(str, 2, 10), new StringSegment(str, 2).TrimEnd('e')); Assert.AreEqual(new StringSegment(str, 3, 9), new StringSegment(str, 3).TrimEnd('e')); Assert.AreEqual(new StringSegment(str, 4, 8), new StringSegment(str, 4).TrimEnd('e')); Assert.AreEqual(new StringSegment(str, 0, 10), new StringSegment(str, 0, 10).TrimEnd('e')); Assert.AreEqual(new StringSegment(str, 0, 9), new StringSegment(str, 0, 9).TrimEnd('e')); Assert.AreEqual(new StringSegment(str, 0, 8), new StringSegment(str, 0, 8).TrimEnd('e')); Assert.AreEqual(new StringSegment(str, 0, 7), new StringSegment(str, 0, 7).TrimEnd('e')); Assert.AreEqual(new StringSegment(str, 3, 6), new StringSegment(str, 3, 6).TrimEnd('e')); } [Test] public void TestToString() { Assert.AreEqual("hey", new StringSegment("hey").ToString()); Assert.AreEqual("ey", new StringSegment("hey", 1).ToString()); Assert.AreEqual("e", new StringSegment("hey", 1, 1).ToString()); } [Test] public void TestToStringBuilder() { Assert.AreEqual("hey", new StringSegment("hey").ToStringBuilder().ToString()); Assert.AreEqual("ey", new StringSegment("hey", 1).ToStringBuilder().ToString()); Assert.AreEqual("e", new StringSegment("hey", 1, 1).ToStringBuilder().ToString()); } [Test] public void TestToStringBuilderNCapacity() { Assert.AreEqual(10, new StringSegment("hey").ToStringBuilder(10).Capacity); } [Test] public void TestUnion() { var str = "01234567"; var segFull = new StringSegment(str); var segFirstHalf = new StringSegment(str, 0, 4); var segLastHalf = new StringSegment(str, 4); var segMiddle = new StringSegment(str, 2, 4); var segSecondChar = new StringSegment(str, 1, 1); var segLastChar = new StringSegment(str, 7, 1); var segCenter = new StringSegment(str, 4, 0); Assert.IsTrue(segFull.Union(segFull).IsIdenticalTo(segFull)); Assert.IsTrue(segFull.Union(segFirstHalf).IsIdenticalTo(segFull)); Assert.IsTrue(segFull.Union(segLastHalf).IsIdenticalTo(segFull)); Assert.IsTrue(segFull.Union(segMiddle).IsIdenticalTo(segFull)); Assert.IsTrue(segFull.Union(segSecondChar).IsIdenticalTo(segFull)); Assert.IsTrue(segFull.Union(segLastChar).IsIdenticalTo(segFull)); Assert.IsTrue(segFull.Union(segCenter).IsIdenticalTo(segFull)); Assert.IsTrue(segFirstHalf.Union(segFull).IsIdenticalTo(segFull)); Assert.IsTrue(segFirstHalf.Union(segFirstHalf).IsIdenticalTo(segFirstHalf)); Assert.IsTrue(segFirstHalf.Union(segLastHalf).IsIdenticalTo(segFull)); Assert.IsTrue(segFirstHalf.Union(segMiddle).IsIdenticalTo(new StringSegment(str, 0, 6))); Assert.IsTrue(segFirstHalf.Union(segSecondChar).IsIdenticalTo(segFirstHalf)); Assert.IsTrue(segFirstHalf.Union(segLastChar).IsIdenticalTo(segFull)); Assert.IsTrue(segFirstHalf.Union(segCenter).IsIdenticalTo(segFirstHalf)); Assert.IsTrue(segLastHalf.Union(segFull).IsIdenticalTo(segFull)); Assert.IsTrue(segLastHalf.Union(segFirstHalf).IsIdenticalTo(segFull)); Assert.IsTrue(segLastHalf.Union(segLastHalf).IsIdenticalTo(segLastHalf)); Assert.IsTrue(segLastHalf.Union(segMiddle).IsIdenticalTo(new StringSegment(str, 2, 6))); Assert.IsTrue(segLastHalf.Union(segSecondChar).IsIdenticalTo(new StringSegment(str, 1, 7))); Assert.IsTrue(segLastHalf.Union(segLastChar).IsIdenticalTo(segLastHalf)); Assert.IsTrue(segLastHalf.Union(segCenter).IsIdenticalTo(segLastHalf)); Assert.IsTrue(segMiddle.Union(segFull).IsIdenticalTo(segFull)); Assert.IsTrue(segMiddle.Union(segFirstHalf).IsIdenticalTo(new StringSegment(str, 0, 6))); Assert.IsTrue(segMiddle.Union(segLastHalf).IsIdenticalTo(new StringSegment(str, 2, 6))); Assert.IsTrue(segMiddle.Union(segMiddle).IsIdenticalTo(segMiddle)); Assert.IsTrue(segMiddle.Union(segSecondChar).IsIdenticalTo(new StringSegment(str, 1, 5))); Assert.IsTrue(segMiddle.Union(segLastChar).IsIdenticalTo(new StringSegment(str, 2, 6))); Assert.IsTrue(segMiddle.Union(segCenter).IsIdenticalTo(segMiddle)); Assert.IsTrue(segSecondChar.Union(segFull).IsIdenticalTo(segFull)); Assert.IsTrue(segSecondChar.Union(segFirstHalf).IsIdenticalTo(segFirstHalf)); Assert.IsTrue(segSecondChar.Union(segLastHalf).IsIdenticalTo(new StringSegment(str, 1, 7))); Assert.IsTrue(segSecondChar.Union(segMiddle).IsIdenticalTo(new StringSegment(str, 1, 5))); Assert.IsTrue(segSecondChar.Union(segSecondChar).IsIdenticalTo(segSecondChar)); Assert.IsTrue(segSecondChar.Union(segLastChar).IsIdenticalTo(new StringSegment(str, 1, 7))); Assert.IsTrue(segSecondChar.Union(segCenter).IsIdenticalTo(new StringSegment(str, 1, 3))); Assert.IsTrue(segLastChar.Union(segFull).IsIdenticalTo(segFull)); Assert.IsTrue(segLastChar.Union(segFirstHalf).IsIdenticalTo(segFull)); Assert.IsTrue(segLastChar.Union(segLastHalf).IsIdenticalTo(segLastHalf)); Assert.IsTrue(segLastChar.Union(segMiddle).IsIdenticalTo(new StringSegment(str, 2, 6))); Assert.IsTrue(segLastChar.Union(segSecondChar).IsIdenticalTo(new StringSegment(str, 1, 7))); Assert.IsTrue(segLastChar.Union(segLastChar).IsIdenticalTo(segLastChar)); Assert.IsTrue(segLastChar.Union(segCenter).IsIdenticalTo(segLastHalf)); Assert.IsTrue(segCenter.Union(segFull).IsIdenticalTo(segFull)); Assert.IsTrue(segCenter.Union(segFirstHalf).IsIdenticalTo(segFirstHalf)); Assert.IsTrue(segCenter.Union(segLastHalf).IsIdenticalTo(segLastHalf)); Assert.IsTrue(segCenter.Union(segMiddle).IsIdenticalTo(segMiddle)); Assert.IsTrue(segCenter.Union(segSecondChar).IsIdenticalTo(new StringSegment(str, 1, 3))); Assert.IsTrue(segCenter.Union(segLastChar).IsIdenticalTo(segLastHalf)); Assert.IsTrue(segCenter.Union(segCenter).IsIdenticalTo(segCenter)); } [Test] public void TestUnionDifferent() { Assert.Throws<ArgumentException>(() => new StringSegment("hey", 1, 2).Union(new StringSegment("eye", 0, 2))); } [Test] public void TestDefaultStringSegment() { var segment = default(StringSegment); Assert.AreEqual(segment.ToString(), ""); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { // Define test collection for tests to avoid all other tests. [CollectionDefinition("NoParallelTests", DisableParallelization = true)] public partial class NoParallelTests { } // Abstract base class for various different socket "modes" (sync, async, etc) // See SendReceive.cs for usage public abstract class SocketHelperBase { public abstract Task<Socket> AcceptAsync(Socket s); public abstract Task<Socket> AcceptAsync(Socket s, Socket acceptSocket); public abstract Task ConnectAsync(Socket s, EndPoint endPoint); public abstract Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port); public abstract Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer); public abstract Task<SocketReceiveFromResult> ReceiveFromAsync( Socket s, ArraySegment<byte> buffer, EndPoint endPoint); public abstract Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList); public abstract Task<int> SendAsync(Socket s, ArraySegment<byte> buffer); public abstract Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList); public abstract Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endpoint); public virtual bool GuaranteedSendOrdering => true; public virtual bool ValidatesArrayArguments => true; public virtual bool UsesSync => false; public virtual bool UsesApm => false; public virtual bool DisposeDuringOperationResultsInDisposedException => false; public virtual bool ConnectAfterDisconnectResultsInInvalidOperationException => false; public virtual bool SupportsMultiConnect => true; public virtual bool SupportsAcceptIntoExistingSocket => true; public virtual void Listen(Socket s, int backlog) { s.Listen(backlog); } } public class SocketHelperArraySync : SocketHelperBase { public override Task<Socket> AcceptAsync(Socket s) => Task.Run(() => s.Accept()); public override Task<Socket> AcceptAsync(Socket s, Socket acceptSocket) => throw new NotSupportedException(); public override Task ConnectAsync(Socket s, EndPoint endPoint) => Task.Run(() => s.Connect(endPoint)); public override Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port) => Task.Run(() => s.Connect(addresses, port)); public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => Task.Run(() => s.Receive(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None)); public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) => Task.Run(() => s.Receive(bufferList, SocketFlags.None)); public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => Task.Run(() => { int received = s.ReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, ref endPoint); return new SocketReceiveFromResult { ReceivedBytes = received, RemoteEndPoint = endPoint }; }); public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => Task.Run(() => s.Send(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None)); public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) => Task.Run(() => s.Send(bufferList, SocketFlags.None)); public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => Task.Run(() => s.SendTo(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, endPoint)); public override bool GuaranteedSendOrdering => false; public override bool UsesSync => true; public override bool ConnectAfterDisconnectResultsInInvalidOperationException => true; public override bool SupportsAcceptIntoExistingSocket => false; } public sealed class SocketHelperSyncForceNonBlocking : SocketHelperArraySync { public override Task<Socket> AcceptAsync(Socket s) => Task.Run(() => { Socket accepted = s.Accept(); accepted.ForceNonBlocking(true); return accepted; }); public override Task ConnectAsync(Socket s, EndPoint endPoint) => Task.Run(() => { s.ForceNonBlocking(true); s.Connect(endPoint); }); public override void Listen(Socket s, int backlog) { s.Listen(backlog); s.ForceNonBlocking(true); } } public sealed class SocketHelperApm : SocketHelperBase { public override bool DisposeDuringOperationResultsInDisposedException => true; public override Task<Socket> AcceptAsync(Socket s) => Task.Factory.FromAsync(s.BeginAccept, s.EndAccept, null); public override Task<Socket> AcceptAsync(Socket s, Socket acceptSocket) => Task.Factory.FromAsync(s.BeginAccept, s.EndAccept, acceptSocket, 0, null); public override Task ConnectAsync(Socket s, EndPoint endPoint) => Task.Factory.FromAsync(s.BeginConnect, s.EndConnect, endPoint, null); public override Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port) => Task.Factory.FromAsync(s.BeginConnect, s.EndConnect, addresses, port, null); public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => Task.Factory.FromAsync((callback, state) => s.BeginReceive(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, callback, state), s.EndReceive, null); public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) => Task.Factory.FromAsync(s.BeginReceive, s.EndReceive, bufferList, SocketFlags.None, null); public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) { var tcs = new TaskCompletionSource<SocketReceiveFromResult>(); s.BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, ref endPoint, iar => { try { int receivedBytes = s.EndReceiveFrom(iar, ref endPoint); tcs.TrySetResult(new SocketReceiveFromResult { ReceivedBytes = receivedBytes, RemoteEndPoint = endPoint }); } catch (Exception e) { tcs.TrySetException(e); } }, null); return tcs.Task; } public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => Task.Factory.FromAsync((callback, state) => s.BeginSend(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, callback, state), s.EndSend, null); public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) => Task.Factory.FromAsync(s.BeginSend, s.EndSend, bufferList, SocketFlags.None, null); public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => Task.Factory.FromAsync( (callback, state) => s.BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, endPoint, callback, state), s.EndSendTo, null); public override bool UsesApm => true; } public class SocketHelperTask : SocketHelperBase { public override Task<Socket> AcceptAsync(Socket s) => s.AcceptAsync(); public override Task<Socket> AcceptAsync(Socket s, Socket acceptSocket) => s.AcceptAsync(acceptSocket); public override Task ConnectAsync(Socket s, EndPoint endPoint) => s.ConnectAsync(endPoint); public override Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port) => s.ConnectAsync(addresses, port); public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => s.ReceiveAsync(buffer, SocketFlags.None); public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) => s.ReceiveAsync(bufferList, SocketFlags.None); public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => s.ReceiveFromAsync(buffer, SocketFlags.None, endPoint); public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => s.SendAsync(buffer, SocketFlags.None); public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) => s.SendAsync(bufferList, SocketFlags.None); public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => s.SendToAsync(buffer, SocketFlags.None, endPoint); } public sealed class SocketHelperEap : SocketHelperBase { public override bool ValidatesArrayArguments => false; public override Task<Socket> AcceptAsync(Socket s) => InvokeAsync(s, e => e.AcceptSocket, e => s.AcceptAsync(e)); public override Task<Socket> AcceptAsync(Socket s, Socket acceptSocket) => InvokeAsync(s, e => e.AcceptSocket, e => { e.AcceptSocket = acceptSocket; return s.AcceptAsync(e); }); public override Task ConnectAsync(Socket s, EndPoint endPoint) => InvokeAsync(s, e => true, e => { e.RemoteEndPoint = endPoint; return s.ConnectAsync(e); }); public override Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port) => throw new NotSupportedException(); public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => InvokeAsync(s, e => e.BytesTransferred, e => { e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); return s.ReceiveAsync(e); }); public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) => InvokeAsync(s, e => e.BytesTransferred, e => { e.BufferList = bufferList; return s.ReceiveAsync(e); }); public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => InvokeAsync(s, e => new SocketReceiveFromResult { ReceivedBytes = e.BytesTransferred, RemoteEndPoint = e.RemoteEndPoint }, e => { e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); e.RemoteEndPoint = endPoint; return s.ReceiveFromAsync(e); }); public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => InvokeAsync(s, e => e.BytesTransferred, e => { e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); return s.SendAsync(e); }); public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) => InvokeAsync(s, e => e.BytesTransferred, e => { e.BufferList = bufferList; return s.SendAsync(e); }); public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => InvokeAsync(s, e => e.BytesTransferred, e => { e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); e.RemoteEndPoint = endPoint; return s.SendToAsync(e); }); private static Task<TResult> InvokeAsync<TResult>( Socket s, Func<SocketAsyncEventArgs, TResult> getResult, Func<SocketAsyncEventArgs, bool> invoke) { var tcs = new TaskCompletionSource<TResult>(); var saea = new SocketAsyncEventArgs(); EventHandler<SocketAsyncEventArgs> handler = (_, e) => { if (e.SocketError == SocketError.Success) tcs.SetResult(getResult(e)); else tcs.SetException(new SocketException((int)e.SocketError)); saea.Dispose(); }; saea.Completed += handler; if (!invoke(saea)) handler(s, saea); return tcs.Task; } public override bool SupportsMultiConnect => false; } public abstract class SocketTestHelperBase<T> : MemberDatas where T : SocketHelperBase, new() { private readonly T _socketHelper; public readonly ITestOutputHelper _output; public SocketTestHelperBase(ITestOutputHelper output) { _socketHelper = new T(); _output = output; } // // Methods that delegate to SocketHelper implementation // public Task<Socket> AcceptAsync(Socket s) => _socketHelper.AcceptAsync(s); public Task<Socket> AcceptAsync(Socket s, Socket acceptSocket) => _socketHelper.AcceptAsync(s, acceptSocket); public Task ConnectAsync(Socket s, EndPoint endPoint) => _socketHelper.ConnectAsync(s, endPoint); public Task MultiConnectAsync(Socket s, IPAddress[] addresses, int port) => _socketHelper.MultiConnectAsync(s, addresses, port); public Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => _socketHelper.ReceiveAsync(s, buffer); public Task<SocketReceiveFromResult> ReceiveFromAsync( Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => _socketHelper.ReceiveFromAsync(s, buffer, endPoint); public Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) => _socketHelper.ReceiveAsync(s, bufferList); public Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => _socketHelper.SendAsync(s, buffer); public Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) => _socketHelper.SendAsync(s, bufferList); public Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endpoint) => _socketHelper.SendToAsync(s, buffer, endpoint); public bool GuaranteedSendOrdering => _socketHelper.GuaranteedSendOrdering; public bool ValidatesArrayArguments => _socketHelper.ValidatesArrayArguments; public bool UsesSync => _socketHelper.UsesSync; public bool UsesApm => _socketHelper.UsesApm; public bool DisposeDuringOperationResultsInDisposedException => _socketHelper.DisposeDuringOperationResultsInDisposedException; public bool ConnectAfterDisconnectResultsInInvalidOperationException => _socketHelper.ConnectAfterDisconnectResultsInInvalidOperationException; public bool SupportsMultiConnect => _socketHelper.SupportsMultiConnect; public bool SupportsAcceptIntoExistingSocket => _socketHelper.SupportsAcceptIntoExistingSocket; public void Listen(Socket s, int backlog) => _socketHelper.Listen(s, backlog); } // // MemberDatas that are generally useful // public abstract class MemberDatas { public static readonly object[][] Loopbacks = new[] { new object[] { IPAddress.Loopback }, new object[] { IPAddress.IPv6Loopback }, }; public static readonly object[][] LoopbacksAndBuffers = new object[][] { new object[] { IPAddress.IPv6Loopback, true }, new object[] { IPAddress.IPv6Loopback, false }, new object[] { IPAddress.Loopback, true }, new object[] { IPAddress.Loopback, false }, }; } // // Utility stuff // internal struct FakeArraySegment { public byte[] Array; public int Offset; public int Count; public ArraySegment<byte> ToActual() { ArraySegmentWrapper wrapper = default(ArraySegmentWrapper); wrapper.Fake = this; return wrapper.Actual; } } [StructLayout(LayoutKind.Explicit)] internal struct ArraySegmentWrapper { [FieldOffset(0)] public ArraySegment<byte> Actual; [FieldOffset(0)] public FakeArraySegment Fake; } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // EncoderBestFitFallback.cs // // This is used internally to create best fit behavior as per the original windows best fit behavior. // namespace System.Text { using System; using System.Globalization; using System.Text; using System.Threading; [Serializable()] internal class InternalEncoderBestFitFallback : EncoderFallback { // Our variables internal Encoding encoding = null; internal char[] arrayBestFit = null; internal InternalEncoderBestFitFallback( Encoding encoding ) { // Need to load our replacement characters table. this.encoding = encoding; this.bIsMicrosoftBestFitFallback = true; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new InternalEncoderBestFitFallbackBuffer( this ); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 1; } } public override bool Equals( Object value ) { InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback; if(that != null) { return (this.encoding.CodePage == that.encoding.CodePage); } return (false); } public override int GetHashCode() { return this.encoding.CodePage; } } internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer { // Our variables private char cBestFit = '\0'; private InternalEncoderBestFitFallback oFallback; private int iCount = -1; private int iSize; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if(s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange( ref s_InternalSyncObject, o, null ); } return s_InternalSyncObject; } } // Constructor public InternalEncoderBestFitFallbackBuffer( InternalEncoderBestFitFallback fallback ) { this.oFallback = fallback; if(oFallback.arrayBestFit == null) { // Lock so we don't confuse ourselves. lock(InternalSyncObject) { // Double check before we do it again. if(oFallback.arrayBestFit == null) { oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); } } } } // Fallback methods public override bool Fallback( char charUnknown, int index ) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. BCLDebug.Assert( iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString( "X4", CultureInfo.InvariantCulture ) + " caused recursive fallback" ); iCount = iSize = 1; cBestFit = TryBestFit( charUnknown ); if(cBestFit == '\0') { cBestFit = '?'; } return true; } public override bool Fallback( char charUnknownHigh, char charUnknownLow, int index ) { // Double check input surrogate pair if(!Char.IsHighSurrogate( charUnknownHigh )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charUnknownHigh", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xD800, 0xDBFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(!Char.IsLowSurrogate( charUnknownLow )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "CharUnknownLow", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xDC00, 0xDFFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. BCLDebug.Assert( iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString( "X4", CultureInfo.InvariantCulture ) + " caused recursive fallback" ); // Go ahead and get our fallback, surrogates don't have best fit cBestFit = '?'; iCount = iSize = 2; return true; } // Default version is overridden in EncoderReplacementFallback.cs public override char GetNextChar() { // Just return cReturn, which is 0 if there's no best fit for it. return (iCount-- > 0) ? cBestFit : '\0'; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. if(iCount >= 0) iCount++; // Return true if we could do it. return (iCount >= 0 && iCount <= iSize); } // How many characters left to output? public override int Remaining { get { return (iCount > 0) ? iCount : 0; } } // Clear the buffer public override unsafe void Reset() { iCount = -1; charStart = null; bFallingBack = false; } // private helper methods private char TryBestFit( char cUnknown ) { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; int highBound = oFallback.arrayBestFit.Length; int index; // Binary search the array int iDiff; while((iDiff = (highBound - lowBound)) > 6) { // Look in the middle, which is complicated by the fact that we have 2 #s for each pair, // so we don't want index to be odd because we want to be on word boundaries. // Also note that index can never == highBound (because diff is rounded down) index = ((iDiff / 2) + lowBound) & 0xFFFE; char cTest = oFallback.arrayBestFit[index]; if(cTest == cUnknown) { // We found it BCLDebug.Assert( index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array" ); return oFallback.arrayBestFit[index + 1]; } else if(cTest < cUnknown) { // We weren't high enough lowBound = index; } else { // We weren't low enough highBound = index; } } for(index = lowBound; index < highBound; index += 2) { if(oFallback.arrayBestFit[index] == cUnknown) { // We found it BCLDebug.Assert( index + 1 < oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array" ); return oFallback.arrayBestFit[index + 1]; } } // Char wasn't in our table return '\0'; } } }