context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// ChunkedUploadResponse
/// </summary>
[DataContract]
public partial class ChunkedUploadResponse : IEquatable<ChunkedUploadResponse>, IValidatableObject
{
public ChunkedUploadResponse()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="ChunkedUploadResponse" /> class.
/// </summary>
/// <param name="Checksum">.</param>
/// <param name="ChunkedUploadId">.</param>
/// <param name="ChunkedUploadParts">.</param>
/// <param name="ChunkedUploadUri">.</param>
/// <param name="Committed">.</param>
/// <param name="ExpirationDateTime">.</param>
/// <param name="MaxChunkedUploadParts">.</param>
/// <param name="MaxTotalSize">.</param>
/// <param name="TotalSize">.</param>
public ChunkedUploadResponse(string Checksum = default(string), string ChunkedUploadId = default(string), List<ChunkedUploadPart> ChunkedUploadParts = default(List<ChunkedUploadPart>), string ChunkedUploadUri = default(string), string Committed = default(string), string ExpirationDateTime = default(string), string MaxChunkedUploadParts = default(string), string MaxTotalSize = default(string), string TotalSize = default(string))
{
this.Checksum = Checksum;
this.ChunkedUploadId = ChunkedUploadId;
this.ChunkedUploadParts = ChunkedUploadParts;
this.ChunkedUploadUri = ChunkedUploadUri;
this.Committed = Committed;
this.ExpirationDateTime = ExpirationDateTime;
this.MaxChunkedUploadParts = MaxChunkedUploadParts;
this.MaxTotalSize = MaxTotalSize;
this.TotalSize = TotalSize;
}
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="checksum", EmitDefaultValue=false)]
public string Checksum { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="chunkedUploadId", EmitDefaultValue=false)]
public string ChunkedUploadId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="chunkedUploadParts", EmitDefaultValue=false)]
public List<ChunkedUploadPart> ChunkedUploadParts { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="chunkedUploadUri", EmitDefaultValue=false)]
public string ChunkedUploadUri { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="committed", EmitDefaultValue=false)]
public string Committed { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="expirationDateTime", EmitDefaultValue=false)]
public string ExpirationDateTime { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="maxChunkedUploadParts", EmitDefaultValue=false)]
public string MaxChunkedUploadParts { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="maxTotalSize", EmitDefaultValue=false)]
public string MaxTotalSize { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="totalSize", EmitDefaultValue=false)]
public string TotalSize { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ChunkedUploadResponse {\n");
sb.Append(" Checksum: ").Append(Checksum).Append("\n");
sb.Append(" ChunkedUploadId: ").Append(ChunkedUploadId).Append("\n");
sb.Append(" ChunkedUploadParts: ").Append(ChunkedUploadParts).Append("\n");
sb.Append(" ChunkedUploadUri: ").Append(ChunkedUploadUri).Append("\n");
sb.Append(" Committed: ").Append(Committed).Append("\n");
sb.Append(" ExpirationDateTime: ").Append(ExpirationDateTime).Append("\n");
sb.Append(" MaxChunkedUploadParts: ").Append(MaxChunkedUploadParts).Append("\n");
sb.Append(" MaxTotalSize: ").Append(MaxTotalSize).Append("\n");
sb.Append(" TotalSize: ").Append(TotalSize).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ChunkedUploadResponse);
}
/// <summary>
/// Returns true if ChunkedUploadResponse instances are equal
/// </summary>
/// <param name="other">Instance of ChunkedUploadResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ChunkedUploadResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Checksum == other.Checksum ||
this.Checksum != null &&
this.Checksum.Equals(other.Checksum)
) &&
(
this.ChunkedUploadId == other.ChunkedUploadId ||
this.ChunkedUploadId != null &&
this.ChunkedUploadId.Equals(other.ChunkedUploadId)
) &&
(
this.ChunkedUploadParts == other.ChunkedUploadParts ||
this.ChunkedUploadParts != null &&
this.ChunkedUploadParts.SequenceEqual(other.ChunkedUploadParts)
) &&
(
this.ChunkedUploadUri == other.ChunkedUploadUri ||
this.ChunkedUploadUri != null &&
this.ChunkedUploadUri.Equals(other.ChunkedUploadUri)
) &&
(
this.Committed == other.Committed ||
this.Committed != null &&
this.Committed.Equals(other.Committed)
) &&
(
this.ExpirationDateTime == other.ExpirationDateTime ||
this.ExpirationDateTime != null &&
this.ExpirationDateTime.Equals(other.ExpirationDateTime)
) &&
(
this.MaxChunkedUploadParts == other.MaxChunkedUploadParts ||
this.MaxChunkedUploadParts != null &&
this.MaxChunkedUploadParts.Equals(other.MaxChunkedUploadParts)
) &&
(
this.MaxTotalSize == other.MaxTotalSize ||
this.MaxTotalSize != null &&
this.MaxTotalSize.Equals(other.MaxTotalSize)
) &&
(
this.TotalSize == other.TotalSize ||
this.TotalSize != null &&
this.TotalSize.Equals(other.TotalSize)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Checksum != null)
hash = hash * 59 + this.Checksum.GetHashCode();
if (this.ChunkedUploadId != null)
hash = hash * 59 + this.ChunkedUploadId.GetHashCode();
if (this.ChunkedUploadParts != null)
hash = hash * 59 + this.ChunkedUploadParts.GetHashCode();
if (this.ChunkedUploadUri != null)
hash = hash * 59 + this.ChunkedUploadUri.GetHashCode();
if (this.Committed != null)
hash = hash * 59 + this.Committed.GetHashCode();
if (this.ExpirationDateTime != null)
hash = hash * 59 + this.ExpirationDateTime.GetHashCode();
if (this.MaxChunkedUploadParts != null)
hash = hash * 59 + this.MaxChunkedUploadParts.GetHashCode();
if (this.MaxTotalSize != null)
hash = hash * 59 + this.MaxTotalSize.GetHashCode();
if (this.TotalSize != null)
hash = hash * 59 + this.TotalSize.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Linq;
using Csla;
using Csla.Data;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// CustomerList (read only list).<br/>
/// This is a generated <see cref="CustomerList"/> business object.
/// This class is a root collection.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="CustomerInfo"/> objects.
/// </remarks>
[Serializable]
#if WINFORMS
public partial class CustomerList : ReadOnlyBindingListBase<CustomerList, CustomerInfo>
#else
public partial class CustomerList : ReadOnlyListBase<CustomerList, CustomerInfo>
#endif
{
#region Event handler properties
[NotUndoable]
private static bool _singleInstanceSavedHandler = true;
/// <summary>
/// Gets or sets a value indicating whether only a single instance should handle the Saved event.
/// </summary>
/// <value>
/// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>.
/// </value>
public static bool SingleInstanceSavedHandler
{
get { return _singleInstanceSavedHandler; }
set { _singleInstanceSavedHandler = value; }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="CustomerList"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="CustomerList"/> collection.</returns>
public static CustomerList GetCustomerList()
{
return DataPortal.Fetch<CustomerList>();
}
/// <summary>
/// Factory method. Loads a <see cref="CustomerList"/> collection, based on given parameters.
/// </summary>
/// <param name="name">The Name parameter of the CustomerList to fetch.</param>
/// <returns>A reference to the fetched <see cref="CustomerList"/> collection.</returns>
public static CustomerList GetCustomerList(string name)
{
return DataPortal.Fetch<CustomerList>(name);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="CustomerList"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetCustomerList(EventHandler<DataPortalResult<CustomerList>> callback)
{
DataPortal.BeginFetch<CustomerList>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="CustomerList"/> collection, based on given parameters.
/// </summary>
/// <param name="name">The Name parameter of the CustomerList to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetCustomerList(string name, EventHandler<DataPortalResult<CustomerList>> callback)
{
DataPortal.BeginFetch<CustomerList>(name, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="CustomerList"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public CustomerList()
{
// Use factory methods and do not use direct creation.
CustomerEditSaved.Register(this);
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = false;
AllowEdit = false;
AllowRemove = false;
RaiseListChangedEvents = rlce;
}
#endregion
#region Saved Event Handler
/// <summary>
/// Handle Saved events of <see cref="CustomerEdit"/> to update the list of <see cref="CustomerInfo"/> objects.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
internal void CustomerEditSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
var obj = (CustomerEdit)e.NewObject;
if (((CustomerEdit)sender).IsNew)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
Add(CustomerInfo.LoadInfo(obj));
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
else if (((CustomerEdit)sender).IsDeleted)
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.CustomerId == obj.CustomerId)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
this.RemoveItem(index);
RaiseListChangedEvents = rlce;
IsReadOnly = true;
break;
}
}
}
else
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.CustomerId == obj.CustomerId)
{
child.UpdatePropertiesOnSaved(obj);
#if !WINFORMS
var notifyCollectionChangedEventArgs =
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index);
OnCollectionChanged(notifyCollectionChangedEventArgs);
#else
var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index);
OnListChanged(listChangedEventArgs);
#endif
break;
}
}
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="CustomerList"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
var args = new DataPortalHookArgs();
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<ICustomerListDal>();
var data = dal.Fetch();
LoadCollection(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads a <see cref="CustomerList"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="name">The Name.</param>
protected void DataPortal_Fetch(string name)
{
var args = new DataPortalHookArgs(name);
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<ICustomerListDal>();
var data = dal.Fetch(name);
LoadCollection(data);
}
OnFetchPost(args);
}
private void LoadCollection(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="CustomerList"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(DataPortal.FetchChild<CustomerInfo>(dr));
}
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
#region CustomerEditSaved nested class
// TODO: edit "CustomerList.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: CustomerEditSaved.Register(this);
/// <summary>
/// Nested class to manage the Saved events of <see cref="CustomerEdit"/>
/// to update the list of <see cref="CustomerInfo"/> objects.
/// </summary>
private static class CustomerEditSaved
{
private static List<WeakReference> _references;
private static bool Found(object obj)
{
return _references.Any(reference => Equals(reference.Target, obj));
}
/// <summary>
/// Registers a CustomerList instance to handle Saved events.
/// to update the list of <see cref="CustomerInfo"/> objects.
/// </summary>
/// <param name="obj">The CustomerList instance.</param>
public static void Register(CustomerList obj)
{
var mustRegister = _references == null;
if (mustRegister)
_references = new List<WeakReference>();
if (CustomerList.SingleInstanceSavedHandler)
_references.Clear();
if (!Found(obj))
_references.Add(new WeakReference(obj));
if (mustRegister)
CustomerEdit.CustomerEditSaved += CustomerEditSavedHandler;
}
/// <summary>
/// Handles Saved events of <see cref="CustomerEdit"/>.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
public static void CustomerEditSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
foreach (var reference in _references)
{
if (reference.IsAlive)
((CustomerList) reference.Target).CustomerEditSavedHandler(sender, e);
}
}
/// <summary>
/// Removes event handling and clears all registered CustomerList instances.
/// </summary>
public static void Unregister()
{
CustomerEdit.CustomerEditSaved -= CustomerEditSavedHandler;
_references = null;
}
}
#endregion
}
}
| |
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 UdemyProject.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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace System
{
public partial class String
{
//
//Native Static Methods
//
private static unsafe int FastCompareStringHelper(uint* strAChars, int countA, uint* strBChars, int countB)
{
int count = (countA < countB) ? countA : countB;
#if BIT64
long diff = (long)((byte*)strAChars - (byte*)strBChars);
#else
int diff = (int)((byte*)strAChars - (byte*)strBChars);
#endif
#if BIT64
int alignmentA = (int)((long)strAChars) & (sizeof(IntPtr) - 1);
int alignmentB = (int)((long)strBChars) & (sizeof(IntPtr) - 1);
if (alignmentA == alignmentB)
{
if ((alignmentA == 2 || alignmentA == 6) && (count >= 1))
{
char* ptr2 = (char*)strBChars;
if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0)
return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2);
strBChars = (uint*)(++ptr2);
count -= 1;
alignmentA = (alignmentA == 2 ? 4 : 0);
}
if ((alignmentA == 4) && (count >= 2))
{
uint* ptr2 = (uint*)strBChars;
if ((*((uint*)((byte*)ptr2 + diff)) - *ptr2) != 0)
{
char* chkptr1 = (char*)((byte*)strBChars + diff);
char* chkptr2 = (char*)strBChars;
if (*chkptr1 != *chkptr2)
return ((int)*chkptr1 - (int)*chkptr2);
return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1));
}
strBChars = ++ptr2;
count -= 2;
alignmentA = 0;
}
if ((alignmentA == 0))
{
while (count >= 4)
{
long* ptr2 = (long*)strBChars;
if ((*((long*)((byte*)ptr2 + diff)) - *ptr2) != 0)
{
if ((*((uint*)((byte*)ptr2 + diff)) - *(uint*)ptr2) != 0)
{
char* chkptr1 = (char*)((byte*)strBChars + diff);
char* chkptr2 = (char*)strBChars;
if (*chkptr1 != *chkptr2)
return ((int)*chkptr1 - (int)*chkptr2);
return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1));
}
else
{
char* chkptr1 = (char*)((uint*)((byte*)strBChars + diff) + 1);
char* chkptr2 = (char*)((uint*)strBChars + 1);
if (*chkptr1 != *chkptr2)
return ((int)*chkptr1 - (int)*chkptr2);
return ((int)*(chkptr1 + 1) - (int)*(chkptr2 + 1));
}
}
strBChars = (uint*)(++ptr2);
count -= 4;
}
}
{
char* ptr2 = (char*)strBChars;
while ((count -= 1) >= 0)
{
if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0)
return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2);
++ptr2;
}
}
}
else
#endif // BIT64
{
#if BIT64
if (Math.Abs(alignmentA - alignmentB) == 4)
{
if ((alignmentA == 2) || (alignmentB == 2))
{
char* ptr2 = (char*)strBChars;
if ((*((char*)((byte*)ptr2 + diff)) - *ptr2) != 0)
return ((int)*((char*)((byte*)ptr2 + diff)) - (int)*ptr2);
strBChars = (uint*)(++ptr2);
count -= 1;
}
}
#endif // BIT64
// Loop comparing a DWORD at a time.
// Reads are potentially unaligned
while ((count -= 2) >= 0)
{
if ((*((uint*)((byte*)strBChars + diff)) - *strBChars) != 0)
{
char* ptr1 = (char*)((byte*)strBChars + diff);
char* ptr2 = (char*)strBChars;
if (*ptr1 != *ptr2)
return ((int)*ptr1 - (int)*ptr2);
return ((int)*(ptr1 + 1) - (int)*(ptr2 + 1));
}
++strBChars;
}
int c;
if (count == -1)
if ((c = *((char*)((byte*)strBChars + diff)) - *((char*)strBChars)) != 0)
return c;
}
return countA - countB;
}
//
//
// NATIVE INSTANCE METHODS
//
//
//
// Search/Query methods
//
//
// Common worker for the various Equality methods. The caller must have already ensured that
// both strings are non-null and that their lengths are equal. Ther caller should also have
// done the Object.ReferenceEquals() fastpath check as we won't repeat it here.
//
private unsafe static bool OrdinalCompareEqualLengthStrings(String strA, String strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
Debug.Assert(strA.Length == strB.Length);
int length = strA.Length;
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
#if BIT64
// Single int read aligns pointers for the following long reads
// PERF: No length check needed as there is always an int32 worth of string allocated
// This read can also include the null terminator which both strings will have
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
// for 64-bit platforms we unroll by 12 and
// check 3 qword at a time. This is less code
// than the 32 bit case and is a shorter path length
while (length >= 12)
{
if (*(long*)a != *(long*)b) goto ReturnFalse;
if (*(long*)(a + 4) != *(long*)(b + 4)) goto ReturnFalse;
if (*(long*)(a + 8) != *(long*)(b + 8)) goto ReturnFalse;
length -= 12; a += 12; b += 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) goto ReturnFalse;
if (*(int*)(a + 2) != *(int*)(b + 2)) goto ReturnFalse;
if (*(int*)(a + 4) != *(int*)(b + 4)) goto ReturnFalse;
if (*(int*)(a + 6) != *(int*)(b + 6)) goto ReturnFalse;
if (*(int*)(a + 8) != *(int*)(b + 8)) goto ReturnFalse;
length -= 10; a += 10; b += 10;
}
#endif
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) goto ReturnFalse;
length -= 2; a += 2; b += 2;
}
return true;
ReturnFalse:
return false;
}
}
private unsafe static bool StartsWithOrdinalHelper(String str, String startsWith)
{
Debug.Assert(str != null);
Debug.Assert(startsWith != null);
Debug.Assert(str.Length >= startsWith.Length);
int length = startsWith.Length;
fixed (char* ap = &str._firstChar) fixed (char* bp = &startsWith._firstChar)
{
char* a = ap;
char* b = bp;
#if BIT64
// Single int read aligns pointers for the following long reads
// No length check needed as this method is called when length >= 2
Debug.Assert(length >= 2);
if (*(int*)a != *(int*)b) goto ReturnFalse;
length -= 2; a += 2; b += 2;
while (length >= 12)
{
if (*(long*)a != *(long*)b) goto ReturnFalse;
if (*(long*)(a + 4) != *(long*)(b + 4)) goto ReturnFalse;
if (*(long*)(a + 8) != *(long*)(b + 8)) goto ReturnFalse;
length -= 12; a += 12; b += 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) goto ReturnFalse;
if (*(int*)(a + 2) != *(int*)(b + 2)) goto ReturnFalse;
if (*(int*)(a + 4) != *(int*)(b + 4)) goto ReturnFalse;
if (*(int*)(a + 6) != *(int*)(b + 6)) goto ReturnFalse;
if (*(int*)(a + 8) != *(int*)(b + 8)) goto ReturnFalse;
length -= 10; a += 10; b += 10;
}
#endif
while (length >= 2)
{
if (*(int*)a != *(int*)b) goto ReturnFalse;
length -= 2; a += 2; b += 2;
}
// PERF: This depends on the fact that the String objects are always zero terminated
// and that the terminating zero is not included in the length. For even string sizes
// this compare can include the zero terminator. Bitwise OR avoids a branch.
return length == 0 | *a == *b;
ReturnFalse:
return false;
}
}
private unsafe static int CompareOrdinalHelper(String strA, String strB)
{
Contract.Requires(strA != null);
Contract.Requires(strB != null);
// NOTE: This may be subject to change if eliminating the check
// in the callers makes them small enough to be inlined
Contract.Assert(strA._firstChar == strB._firstChar,
"For performance reasons, callers of this method should " +
"check/short-circuit beforehand if the first char is the same.");
int length = Math.Min(strA.Length, strB.Length);
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
// Check if the second chars are different here
// The reason we check if _firstChar is different is because
// it's the most common case and allows us to avoid a method call
// to here.
// The reason we check if the second char is different is because
// if the first two chars the same we can increment by 4 bytes,
// leaving us word-aligned on both 32-bit (12 bytes into the string)
// and 64-bit (16 bytes) platforms.
// For empty strings, the second char will be null due to padding.
// The start of the string is the EE type pointer + string length,
// which takes up 8 bytes on 32-bit, 12 on x64. For empty strings,
// the null terminator immediately follows, leaving us with an object
// 10/14 bytes in size. Since everything needs to be a multiple
// of 4/8, this will get padded and zeroed out.
// For one-char strings the second char will be the null terminator.
// NOTE: If in the future there is a way to read the second char
// without pinning the string (e.g. System.Runtime.CompilerServices.Unsafe
// is exposed to mscorlib, or a future version of C# allows inline IL),
// then do that and short-circuit before the fixed.
if (*(a + 1) != *(b + 1)) goto DiffOffset1;
// Since we know that the first two chars are the same,
// we can increment by 2 here and skip 4 bytes.
// This leaves us 8-byte aligned, which results
// on better perf for 64-bit platforms.
length -= 2; a += 2; b += 2;
// unroll the loop
#if BIT64
while (length >= 12)
{
if (*(long*)a != *(long*)b) goto DiffOffset0;
if (*(long*)(a + 4) != *(long*)(b + 4)) goto DiffOffset4;
if (*(long*)(a + 8) != *(long*)(b + 8)) goto DiffOffset8;
length -= 12; a += 12; b += 12;
}
#else // BIT64
while (length >= 10)
{
if (*(int*)a != *(int*)b) goto DiffOffset0;
if (*(int*)(a + 2) != *(int*)(b + 2)) goto DiffOffset2;
if (*(int*)(a + 4) != *(int*)(b + 4)) goto DiffOffset4;
if (*(int*)(a + 6) != *(int*)(b + 6)) goto DiffOffset6;
if (*(int*)(a + 8) != *(int*)(b + 8)) goto DiffOffset8;
length -= 10; a += 10; b += 10;
}
#endif // BIT64
// Fallback loop:
// go back to slower code path and do comparison on 4 bytes at a time.
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) goto DiffNextInt;
length -= 2;
a += 2;
b += 2;
}
// At this point, we have compared all the characters in at least one string.
// The longer string will be larger.
return strA.Length - strB.Length;
#if BIT64
DiffOffset8: a += 4; b += 4;
DiffOffset4: a += 4; b += 4;
#else // BIT64
// Use jumps instead of falling through, since
// otherwise going to DiffOffset8 will involve
// 8 add instructions before getting to DiffNextInt
DiffOffset8: a += 8; b += 8; goto DiffOffset0;
DiffOffset6: a += 6; b += 6; goto DiffOffset0;
DiffOffset4: a += 2; b += 2;
DiffOffset2: a += 2; b += 2;
#endif // BIT64
DiffOffset0:
// If we reached here, we already see a difference in the unrolled loop above
#if BIT64
if (*(int*)a == *(int*)b)
{
a += 2; b += 2;
}
#endif // BIT64
DiffNextInt:
if (*a != *b) return *a - *b;
DiffOffset1:
Contract.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
return *(a + 1) - *(b + 1);
}
}
internal unsafe static int CompareOrdinalHelper(string strA, int indexA, int countA, string strB, int indexB, int countB)
{
// Argument validation should be handled by callers.
Contract.Assert(strA != null && strB != null);
Contract.Assert(indexA >= 0 && indexB >= 0);
Contract.Assert(countA >= 0 && countB >= 0);
Contract.Assert(countA <= strA.Length - indexA);
Contract.Assert(countB <= strB.Length - indexB);
// Set up the loop variables.
fixed (char* pStrA = &strA._firstChar, pStrB = &strB._firstChar)
{
char* strAChars = pStrA + indexA;
char* strBChars = pStrB + indexB;
return FastCompareStringHelper((uint*)strAChars, countA, (uint*)strBChars, countB);
}
}
public static int Compare(String strA, String strB)
{
return Compare(strA, strB, StringComparison.CurrentCulture);
}
public static int Compare(String strA, String strB, bool ignoreCase)
{
var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
return Compare(strA, strB, comparisonType);
}
// Provides a more flexible function for string comparision. See StringComparison
// for meaning of different comparisonType.
public static int Compare(String strA, String strB, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
}
if (object.ReferenceEquals(strA, strB))
{
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
return -1;
}
if (strB == null)
{
return 1;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return FormatProvider.Compare(strA, 0, strA.Length, strB, 0, strB.Length);
case StringComparison.CurrentCultureIgnoreCase:
return FormatProvider.CompareIgnoreCase(strA, 0, strA.Length, strB, 0, strB.Length);
case StringComparison.Ordinal:
// Most common case: first character is different.
// Returns false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
case StringComparison.OrdinalIgnoreCase:
return FormatProvider.CompareOrdinalIgnoreCase(strA, 0, strA.Length, strB, 0, strB.Length);
default:
throw new NotSupportedException(SR.NotSupported_StringComparison);
}
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length)
{
// NOTE: It's important we call the boolean overload, and not the StringComparison
// one. The two have some subtly different behavior (see notes in the former).
return Compare(strA, indexA, strB, indexB, length, ignoreCase: false);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length count is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase)
{
// Ideally we would just forward to the string.Compare overload that takes
// a StringComparison parameter, and just pass in CurrentCulture/CurrentCultureIgnoreCase.
// That function will return early if an optimization can be applied, e.g. if
// (object)strA == strB && indexA == indexB then it will return 0 straightaway.
// There are a couple of subtle behavior differences that prevent us from doing so
// however:
// - string.Compare(null, -1, null, -1, -1, StringComparison.CurrentCulture) works
// since that method also returns early for nulls before validation. It shouldn't
// for this overload.
// - Since we originally forwarded to FormatProvider for all of the argument
// validation logic, the ArgumentOutOfRangeExceptions thrown will contain different
// parameter names.
// Therefore, we have to duplicate some of the logic here.
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
return ignoreCase ?
FormatProvider.CompareIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB) :
FormatProvider.Compare(strA, indexA, lengthA, strB, indexB, lengthB);
}
public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
}
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
// @TODO: Spec#: Figure out what to do here with the return statement above.
if (length < 0)
{
throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeLength);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? "indexA" : "indexB";
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (strA.Length - indexA < 0 || strB.Length - indexB < 0)
{
string paramName = strA.Length - indexA < 0 ? "indexA" : "indexB";
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return FormatProvider.Compare(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.CurrentCultureIgnoreCase:
return FormatProvider.CompareIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.Ordinal:
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.OrdinalIgnoreCase:
return FormatProvider.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB);
default:
throw new ArgumentException(SR.NotSupported_StringComparison);
}
}
// Compares strA and strB using an ordinal (code-point) comparison.
//
public static int CompareOrdinal(String strA, String strB)
{
if (object.ReferenceEquals(strA, strB))
{
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
return -1;
}
if (strB == null)
{
return 1;
}
// Most common case, first character is different.
// This will return false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
}
public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length)
{
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
// COMPAT: Checking for nulls should become before the arguments are validated,
// but other optimizations which allow us to return early should come after.
if (length < 0)
{
throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeCount);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? "indexA" : "indexB";
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
if (lengthA < 0 || lengthB < 0)
{
string paramName = lengthA < 0 ? "indexA" : "indexB";
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
}
// Compares this String to another String (cast as object), returning an integer that
// indicates the relationship. This method returns a value less than 0 if this is less than value, 0
// if this is equal to value, or a value greater than 0 if this is greater than value.
//
int IComparable.CompareTo(Object value)
{
if (value == null)
{
return 1;
}
string other = value as string;
if (other == null)
{
throw new ArgumentException(SR.Arg_MustBeString);
}
return CompareTo(other); // will call the string-based overload
}
// Determines the sorting relation of StrB to the current instance.
//
public int CompareTo(String strB)
{
return string.Compare(this, strB, StringComparison.CurrentCulture);
}
// Determines whether a specified string is a suffix of the the current instance.
//
// The case-sensitive and culture-sensitive option is set by options,
// and the default culture is used.
//
public Boolean EndsWith(String value)
{
return EndsWith(value, StringComparison.CurrentCulture);
}
public Boolean EndsWith(String value, StringComparison comparisonType)
{
if ((Object)value == null)
{
throw new ArgumentNullException("value");
}
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
}
if ((Object)this == (Object)value)
{
return true;
}
if (value.Length == 0)
{
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return FormatProvider.IsSuffix(this, value);
case StringComparison.CurrentCultureIgnoreCase:
return FormatProvider.IsSuffixIgnoreCase(this, value);
case StringComparison.Ordinal:
return this.Length < value.Length ? false : (CompareOrdinalHelper(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
case StringComparison.OrdinalIgnoreCase:
return this.Length < value.Length ? false : (FormatProvider.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
}
}
internal bool EndsWith(char value)
{
int thisLen = this.Length;
if (thisLen != 0)
{
if (this[thisLen - 1] == value)
return true;
}
return false;
}
// Determines whether two strings match.
public override bool Equals(Object obj)
{
if (Object.ReferenceEquals(this, obj))
return true;
String str = obj as String;
if (str == null)
return false;
if (this.Length != str.Length)
return false;
return OrdinalCompareEqualLengthStrings(this, str);
}
// Determines whether two strings match.
public bool Equals(String value)
{
if (Object.ReferenceEquals(this, value))
return true;
// NOTE: No need to worry about casting to object here.
// If either side of an == comparison between strings
// is null, Roslyn generates a simple ceq instruction
// instead of calling string.op_Equality.
if (value == null)
return false;
if (this.Length != value.Length)
return false;
return OrdinalCompareEqualLengthStrings(this, value);
}
public bool Equals(String value, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
if ((Object)this == (Object)value)
{
return true;
}
if ((Object)value == null)
{
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (FormatProvider.Compare(this, 0, this.Length, value, 0, value.Length) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (FormatProvider.CompareIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0);
case StringComparison.Ordinal:
if (this.Length != value.Length)
return false;
return OrdinalCompareEqualLengthStrings(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length != value.Length)
return false;
else
{
return FormatProvider.CompareOrdinalIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0;
}
default:
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
}
}
// Determines whether two Strings match.
public static bool Equals(String a, String b)
{
if ((Object)a == (Object)b)
{
return true;
}
if ((Object)a == null || (Object)b == null || a.Length != b.Length)
{
return false;
}
return OrdinalCompareEqualLengthStrings(a, b);
}
public static bool Equals(String a, String b, StringComparison comparisonType)
{
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
if ((Object)a == (Object)b)
{
return true;
}
if ((Object)a == null || (Object)b == null)
{
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (FormatProvider.Compare(a, 0, a.Length, b, 0, b.Length) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (FormatProvider.CompareIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0);
case StringComparison.Ordinal:
if (a.Length != b.Length)
return false;
return OrdinalCompareEqualLengthStrings(a, b);
case StringComparison.OrdinalIgnoreCase:
if (a.Length != b.Length)
return false;
else
{
return FormatProvider.CompareOrdinalIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0;
}
default:
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
}
}
public static bool operator ==(String a, String b)
{
if (Object.ReferenceEquals(a, b))
return true;
if (a == null || b == null || a.Length != b.Length)
return false;
return OrdinalCompareEqualLengthStrings(a, b);
}
public static bool operator !=(String a, String b)
{
if (Object.ReferenceEquals(a, b))
return false;
if (a == null || b == null || a.Length != b.Length)
return true;
return !OrdinalCompareEqualLengthStrings(a, b);
}
// Gets a hash code for this string. If strings A and B are such that A.Equals(B), then
// they will return the same hash code.
public override int GetHashCode()
{
unsafe
{
fixed (char* src = &_firstChar)
{
#if BIT64
int hash1 = 5381;
#else
int hash1 = (5381 << 16) + 5381;
#endif
int hash2 = hash1;
#if BIT64
int c;
char* s = src;
while ((c = s[0]) != 0)
{
hash1 = ((hash1 << 5) + hash1) ^ c;
c = s[1];
if (c == 0)
break;
hash2 = ((hash2 << 5) + hash2) ^ c;
s += 2;
}
#else
// 32bit machines.
int* pint = (int*)src;
int len = this.Length;
while (len > 0)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
if (len <= 2)
{
break;
}
hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1];
pint += 2;
len -= 4;
}
#endif
return hash1 + (hash2 * 1566083941);
}
}
}
// Determines whether a specified string is a prefix of the current instance
//
public Boolean StartsWith(String value)
{
if ((Object)value == null)
{
throw new ArgumentNullException("value");
}
return StartsWith(value, StringComparison.CurrentCulture);
}
public Boolean StartsWith(String value, StringComparison comparisonType)
{
if ((Object)value == null)
{
throw new ArgumentNullException("value");
}
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
{
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
}
if ((Object)this == (Object)value)
{
return true;
}
if (value.Length == 0)
{
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return FormatProvider.IsPrefix(this, value);
case StringComparison.CurrentCultureIgnoreCase:
return FormatProvider.IsPrefixIgnoreCase(this, value);
case StringComparison.Ordinal:
if (this.Length < value.Length || _firstChar != value._firstChar)
{
return false;
}
return (value.Length == 1) ?
true : // First char is the same and thats all there is to compare
StartsWithOrdinalHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length < value.Length)
{
return false;
}
return FormatProvider.CompareOrdinalIgnoreCase(this, 0, value.Length, value, 0, value.Length) == 0;
default:
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.CoreModules.World.Wind.Plugins
{
[Extension(Path = "/OpenSim/WindModule", NodeName = "WindModel", Id = "ConfigurableWind")]
class ConfigurableWind : Mono.Addins.TypeExtensionNode, IWindModelPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Vector2[] m_windSpeeds = new Vector2[16 * 16];
//private Random m_rndnums = new Random(Environment.TickCount);
private float m_avgStrength = 5.0f; // Average magnitude of the wind vector
private float m_avgDirection = 0.0f; // Average direction of the wind in degrees
private float m_varStrength = 5.0f; // Max Strength Variance
private float m_varDirection = 30.0f;// Max Direction Variance
private float m_rateChange = 1.0f; //
private Vector2 m_curPredominateWind = new Vector2();
#region IPlugin Members
public string Version
{
get { return "1.0.0.0"; }
}
public string Name
{
get { return "ConfigurableWind"; }
}
public void Initialise()
{
}
#endregion
#region IDisposable Members
public void Dispose()
{
m_windSpeeds = null;
}
#endregion
#region IWindModelPlugin Members
public void WindConfig(OpenSim.Region.Framework.Scenes.Scene scene, Nini.Config.IConfig windConfig)
{
if (windConfig != null)
{
// Uses strength value if avg_strength not specified
m_avgStrength = windConfig.GetFloat("strength", 5.0F);
m_avgStrength = windConfig.GetFloat("avg_strength", m_avgStrength);
m_avgDirection = windConfig.GetFloat("avg_direction", 0.0F);
m_varStrength = windConfig.GetFloat("var_strength", 5.0F);
m_varDirection = windConfig.GetFloat("var_direction", 30.0F);
m_rateChange = windConfig.GetFloat("rate_change", 1.0F);
LogSettings();
}
}
public void WindUpdate(uint frame)
{
double avgAng = m_avgDirection * (Math.PI/180.0f);
double varDir = m_varDirection * (Math.PI/180.0f);
// Prevailing wind algorithm
// Inspired by Kanker Greenacre
// TODO:
// * This should probably be based on in-world time.
// * should probably move all these local variables to class members and constants
double time = DateTime.Now.TimeOfDay.Seconds / 86400.0f;
double theta = time * (2 * Math.PI) * m_rateChange;
double offset = Math.Sin(theta) * Math.Sin(theta*2) * Math.Sin(theta*9) * Math.Cos(theta*4);
double windDir = avgAng + (varDir * offset);
offset = Math.Sin(theta) * Math.Sin(theta*4) + (Math.Sin(theta*13) / 3);
double windSpeed = m_avgStrength + (m_varStrength * offset);
if (windSpeed<0)
windSpeed=0;
m_curPredominateWind.X = (float)Math.Cos(windDir);
m_curPredominateWind.Y = (float)Math.Sin(windDir);
m_curPredominateWind.Normalize();
m_curPredominateWind.X *= (float)windSpeed;
m_curPredominateWind.Y *= (float)windSpeed;
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x++)
{
m_windSpeeds[y * 16 + x] = m_curPredominateWind;
}
}
}
public Vector3 WindSpeed(float fX, float fY, float fZ)
{
return new Vector3(m_curPredominateWind, 0.0f);
}
public Vector2[] WindLLClientArray()
{
return m_windSpeeds;
}
public string Description
{
get
{
return "Provides a predominate wind direction that can change within configured variances for direction and speed.";
}
}
public System.Collections.Generic.Dictionary<string, string> WindParams()
{
Dictionary<string, string> Params = new Dictionary<string, string>();
Params.Add("avgStrength", "average wind strength");
Params.Add("avgDirection", "average wind direction in degrees");
Params.Add("varStrength", "allowable variance in wind strength");
Params.Add("varDirection", "allowable variance in wind direction in +/- degrees");
Params.Add("rateChange", "rate of change");
return Params;
}
public void WindParamSet(string param, float value)
{
switch (param)
{
case "avgStrength":
m_avgStrength = value;
break;
case "avgDirection":
m_avgDirection = value;
break;
case "varStrength":
m_varStrength = value;
break;
case "varDirection":
m_varDirection = value;
break;
case "rateChange":
m_rateChange = value;
break;
}
}
public float WindParamGet(string param)
{
switch (param)
{
case "avgStrength":
return m_avgStrength;
case "avgDirection":
return m_avgDirection;
case "varStrength":
return m_varStrength;
case "varDirection":
return m_varDirection;
case "rateChange":
return m_rateChange;
default:
throw new Exception(String.Format("Unknown {0} parameter {1}", this.Name, param));
}
}
#endregion
private void LogSettings()
{
m_log.InfoFormat("[ConfigurableWind] Average Strength : {0}", m_avgStrength);
m_log.InfoFormat("[ConfigurableWind] Average Direction : {0}", m_avgDirection);
m_log.InfoFormat("[ConfigurableWind] Varience Strength : {0}", m_varStrength);
m_log.InfoFormat("[ConfigurableWind] Varience Direction : {0}", m_varDirection);
m_log.InfoFormat("[ConfigurableWind] Rate Change : {0}", m_rateChange);
}
#region IWindModelPlugin Members
#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.
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Xml;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Security;
using System.Linq;
#if USE_REFEMIT || NET_NATIVE
public sealed class ClassDataContract : DataContract
#else
internal sealed class ClassDataContract : DataContract
#endif
{
/// <SecurityNote>
/// Review - XmlDictionaryString(s) representing the XML namespaces for class members.
/// statically cached and used from IL generated code. should ideally be Critical.
/// marked SecurityRequiresReview to be callable from transparent IL generated code.
/// not changed to property to avoid regressing performance; any changes to initalization should be reviewed.
/// </SecurityNote>
public XmlDictionaryString[] ContractNamespaces;
/// <SecurityNote>
/// Review - XmlDictionaryString(s) representing the XML element names for class members.
/// statically cached and used from IL generated code. should ideally be Critical.
/// marked SecurityRequiresReview to be callable from transparent IL generated code.
/// not changed to property to avoid regressing performance; any changes to initalization should be reviewed.
/// </SecurityNote>
public XmlDictionaryString[] MemberNames;
/// <SecurityNote>
/// Review - XmlDictionaryString(s) representing the XML namespaces for class members.
/// statically cached and used when calling IL generated code. should ideally be Critical.
/// marked SecurityRequiresReview to be callable from transparent code.
/// not changed to property to avoid regressing performance; any changes to initalization should be reviewed.
/// </SecurityNote>
public XmlDictionaryString[] MemberNamespaces;
[SecurityCritical]
/// <SecurityNote>
/// Critical - XmlDictionaryString representing the XML namespaces for members of class.
/// statically cached and used from IL generated code.
/// </SecurityNote>
private XmlDictionaryString[] _childElementNamespaces;
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
private ClassDataContractCriticalHelper _helper;
private bool _isScriptObject;
#if NET_NATIVE
public ClassDataContract() : base(new ClassDataContractCriticalHelper())
{
InitClassDataContract();
}
#endif
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
internal ClassDataContract(Type type) : base(new ClassDataContractCriticalHelper(type))
{
InitClassDataContract();
}
[SecuritySafeCritical]
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
private ClassDataContract(Type type, XmlDictionaryString ns, string[] memberNames) : base(new ClassDataContractCriticalHelper(type, ns, memberNames))
{
InitClassDataContract();
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - initializes SecurityCritical fields; called from all constructors
/// </SecurityNote>
private void InitClassDataContract()
{
_helper = base.Helper as ClassDataContractCriticalHelper;
this.ContractNamespaces = _helper.ContractNamespaces;
this.MemberNames = _helper.MemberNames;
this.MemberNamespaces = _helper.MemberNamespaces;
_isScriptObject = _helper.IsScriptObject;
}
internal ClassDataContract BaseContract
{
/// <SecurityNote>
/// Critical - fetches the critical baseContract property
/// Safe - baseContract only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.BaseContract; }
}
internal List<DataMember> Members
{
/// <SecurityNote>
/// Critical - fetches the critical members property
/// Safe - members only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.Members; }
}
public XmlDictionaryString[] ChildElementNamespaces
{
/// <SecurityNote>
/// Critical - fetches the critical childElementNamespaces property
/// Safe - childElementNamespaces only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_childElementNamespaces == null)
{
lock (this)
{
if (_childElementNamespaces == null)
{
if (_helper.ChildElementNamespaces == null)
{
XmlDictionaryString[] tempChildElementamespaces = CreateChildElementNamespaces();
Interlocked.MemoryBarrier();
_helper.ChildElementNamespaces = tempChildElementamespaces;
}
_childElementNamespaces = _helper.ChildElementNamespaces;
}
}
}
return _childElementNamespaces;
}
#if NET_NATIVE
set
{
_childElementNamespaces = value;
}
#endif
}
internal MethodInfo OnSerializing
{
/// <SecurityNote>
/// Critical - fetches the critical onSerializing property
/// Safe - onSerializing only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnSerializing; }
}
internal MethodInfo OnSerialized
{
/// <SecurityNote>
/// Critical - fetches the critical onSerialized property
/// Safe - onSerialized only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnSerialized; }
}
internal MethodInfo OnDeserializing
{
/// <SecurityNote>
/// Critical - fetches the critical onDeserializing property
/// Safe - onDeserializing only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnDeserializing; }
}
internal MethodInfo OnDeserialized
{
/// <SecurityNote>
/// Critical - fetches the critical onDeserialized property
/// Safe - onDeserialized only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnDeserialized; }
}
#if !NET_NATIVE
public override DataContractDictionary KnownDataContracts
{
/// <SecurityNote>
/// Critical - fetches the critical knownDataContracts property
/// Safe - knownDataContracts only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.KnownDataContracts; }
}
#endif
internal bool IsNonAttributedType
{
/// <SecurityNote>
/// Critical - fetches the critical IsNonAttributedType property
/// Safe - IsNonAttributedType only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.IsNonAttributedType; }
}
#if NET_NATIVE
public bool HasDataContract
{
[SecuritySafeCritical]
get
{ return _helper.HasDataContract; }
set { _helper.HasDataContract = value; }
}
public bool HasExtensionData
{
[SecuritySafeCritical]
get
{ return _helper.HasExtensionData; }
set { _helper.HasExtensionData = value; }
}
#endif
internal bool IsKeyValuePairAdapter
{
[SecuritySafeCritical]
get
{ return _helper.IsKeyValuePairAdapter; }
}
internal Type[] KeyValuePairGenericArguments
{
[SecuritySafeCritical]
get
{ return _helper.KeyValuePairGenericArguments; }
}
internal ConstructorInfo KeyValuePairAdapterConstructorInfo
{
[SecuritySafeCritical]
get
{ return _helper.KeyValuePairAdapterConstructorInfo; }
}
internal MethodInfo GetKeyValuePairMethodInfo
{
[SecuritySafeCritical]
get
{ return _helper.GetKeyValuePairMethodInfo; }
}
/// <SecurityNote>
/// Critical - fetches information about which constructor should be used to initialize non-attributed types that are valid for serialization
/// Safe - only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
internal ConstructorInfo GetNonAttributedTypeConstructor()
{
return _helper.GetNonAttributedTypeConstructor();
}
#if !NET_NATIVE
internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate
{
/// <SecurityNote>
/// Critical - fetches the critical xmlFormatWriterDelegate property
/// Safe - xmlFormatWriterDelegate only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatWriterDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatWriterDelegate == null)
{
XmlFormatClassWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateClassWriter(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatWriterDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatWriterDelegate;
}
}
#else
public XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get; set; }
#endif
#if !NET_NATIVE
internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate
{
/// <SecurityNote>
/// Critical - fetches the critical xmlFormatReaderDelegate property
/// Safe - xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatReaderDelegate == null)
{
XmlFormatClassReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateClassReader(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatReaderDelegate;
}
}
#else
public XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get; set; }
#endif
internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames)
{
#if !NET_NATIVE
return new ClassDataContract(type, ns, memberNames);
#else
ClassDataContract cdc = (ClassDataContract)DataContract.GetDataContractFromGeneratedAssembly(type);
ClassDataContract cloned = cdc.Clone();
cloned.UpdateNamespaceAndMembers(type, ns, memberNames);
return cloned;
#endif
}
internal static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable)
{
DataMember existingMemberContract;
if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract))
{
Type declaringType = memberContract.MemberInfo.DeclaringType;
DataContract.ThrowInvalidDataContractException(
SR.Format((declaringType.GetTypeInfo().IsEnum ? SR.DupEnumMemberValue : SR.DupMemberName),
existingMemberContract.MemberInfo.Name,
memberContract.MemberInfo.Name,
DataContract.GetClrTypeFullName(declaringType),
memberContract.Name),
declaringType);
}
memberNamesTable.Add(memberContract.Name, memberContract);
members.Add(memberContract);
}
internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary)
{
childType = DataContract.UnwrapNullableType(childType);
if (!childType.GetTypeInfo().IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType)
&& DataContract.GetBuiltInDataContract(childType) == null && childType != Globals.TypeOfDBNull)
{
string ns = DataContract.GetStableName(childType).Namespace;
if (ns.Length > 0 && ns != dataContract.Namespace.Value)
return dictionary.Add(ns);
}
return null;
}
private static bool IsArraySegment(Type t)
{
return t.GetTypeInfo().IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
/// <SecurityNote>
/// RequiresReview - callers may need to depend on isNonAttributedType for a security decision
/// isNonAttributedType must be calculated correctly
/// IsNonAttributedTypeValidForSerialization is used as part of the isNonAttributedType calculation and
/// is therefore marked SRR
/// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value
/// </SecurityNote>
static internal bool IsNonAttributedTypeValidForSerialization(Type type)
{
if (type.IsArray)
return false;
if (type.GetTypeInfo().IsEnum)
return false;
if (type.IsGenericParameter)
return false;
if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))
return false;
if (type.IsPointer)
return false;
if (type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
return false;
Type[] interfaceTypes = type.GetInterfaces();
if (!IsArraySegment(type))
{
foreach (Type interfaceType in interfaceTypes)
{
if (CollectionDataContract.IsCollectionInterface(interfaceType))
return false;
}
}
if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false))
return false;
if (type.GetTypeInfo().IsValueType)
{
return type.GetTypeInfo().IsVisible;
}
else
{
return (type.GetTypeInfo().IsVisible &&
type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()) != null);
}
}
private static readonly Dictionary<string, string[]> s_knownSerializableTypeInfos = new Dictionary<string, string[]> {
{ "System.Collections.Generic.KeyValuePair`2", Array.Empty<string>() },
{ "System.Collections.Generic.Queue`1", new [] { "_syncRoot" } },
{ "System.Collections.Generic.Stack`1", new [] {"_syncRoot" } },
{ "System.Collections.ObjectModel.ReadOnlyCollection`1", new [] {"_syncRoot" } },
{ "System.Collections.ObjectModel.ReadOnlyDictionary`2", new [] {"_syncRoot", "_keys","_values" } },
{ "System.Tuple`1", Array.Empty<string>() },
{ "System.Tuple`2", Array.Empty<string>() },
{ "System.Tuple`3", Array.Empty<string>() },
{ "System.Tuple`4", Array.Empty<string>() },
{ "System.Tuple`5", Array.Empty<string>() },
{ "System.Tuple`6", Array.Empty<string>() },
{ "System.Tuple`7", Array.Empty<string>() },
{ "System.Tuple`8", Array.Empty<string>() },
{ "System.Collections.Queue", new [] {"_syncRoot" } },
{ "System.Collections.Stack", new [] {"_syncRoot" } },
{ "System.Globalization.CultureInfo", Array.Empty<string>() },
{ "System.Version", Array.Empty<string>() },
};
private static string GetGeneralTypeName(Type type)
{
TypeInfo typeInfo = type.GetTypeInfo();
return typeInfo.IsGenericType && !typeInfo.IsGenericParameter
? typeInfo.GetGenericTypeDefinition().FullName
: type.FullName;
}
internal static bool IsKnownSerializableType(Type type)
{
// Applies to known types that DCS understands how to serialize/deserialize
//
string typeFullName = GetGeneralTypeName(type);
return s_knownSerializableTypeInfos.ContainsKey(typeFullName)
|| Globals.TypeOfException.IsAssignableFrom(type);
}
internal static bool IsNonSerializedMember(Type type, string memberName)
{
string typeFullName = GetGeneralTypeName(type);
string[] members;
return s_knownSerializableTypeInfos.TryGetValue(typeFullName, out members)
&& members.Contains(memberName);
}
private XmlDictionaryString[] CreateChildElementNamespaces()
{
if (Members == null)
return null;
XmlDictionaryString[] baseChildElementNamespaces = null;
if (this.BaseContract != null)
baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces;
int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0;
XmlDictionaryString[] childElementNamespaces = new XmlDictionaryString[Members.Count + baseChildElementNamespaceCount];
if (baseChildElementNamespaceCount > 0)
Array.Copy(baseChildElementNamespaces, 0, childElementNamespaces, 0, baseChildElementNamespaces.Length);
XmlDictionary dictionary = new XmlDictionary();
for (int i = 0; i < this.Members.Count; i++)
{
childElementNamespaces[i + baseChildElementNamespaceCount] = GetChildNamespaceToDeclare(this, this.Members[i].MemberType, dictionary);
}
return childElementNamespaces;
}
[SecuritySafeCritical]
/// <SecurityNote>
/// Critical - calls critical method on helper
/// Safe - doesn't leak anything
/// </SecurityNote>
private void EnsureMethodsImported()
{
_helper.EnsureMethodsImported();
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
if (_isScriptObject)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
}
XmlFormatWriterDelegate(xmlWriter, obj, context, this);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
if (_isScriptObject)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
}
xmlReader.Read();
object o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces);
xmlReader.ReadEndElement();
return o;
}
/// <SecurityNote>
/// Review - calculates whether this class requires MemberAccessPermission for deserialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForRead(SecurityException securityException)
{
EnsureMethodsImported();
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForRead(securityException))
return true;
if (ConstructorRequiresMemberAccess(GetNonAttributedTypeConstructor()))
{
if (Globals.TypeOfScriptObject_IsAssignableFrom(UnderlyingType))
{
return true;
}
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustNonAttributedSerializableTypeNoPublicConstructor,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.OnDeserializing))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnDeserializingNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.OnDeserializing.Name),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.OnDeserialized))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnDeserializedNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.OnDeserialized.Name),
securityException));
}
return true;
}
if (this.Members != null)
{
for (int i = 0; i < this.Members.Count; i++)
{
if (this.Members[i].RequiresMemberAccessForSet())
{
if (securityException != null)
{
if (this.Members[i].MemberInfo is FieldInfo)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractFieldSetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractPropertySetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
}
return true;
}
}
}
return false;
}
/// <SecurityNote>
/// Review - calculates whether this class requires MemberAccessPermission for serialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForWrite(SecurityException securityException)
{
EnsureMethodsImported();
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForWrite(securityException))
return true;
if (MethodRequiresMemberAccess(this.OnSerializing))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnSerializingNotPublic,
DataContract.GetClrTypeFullName(this.UnderlyingType),
this.OnSerializing.Name),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.OnSerialized))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnSerializedNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.OnSerialized.Name),
securityException));
}
return true;
}
if (this.Members != null)
{
for (int i = 0; i < this.Members.Count; i++)
{
if (this.Members[i].RequiresMemberAccessForGet())
{
if (securityException != null)
{
if (this.Members[i].MemberInfo is FieldInfo)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractFieldGetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractPropertyGetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
}
return true;
}
}
}
return false;
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds all state used for (de)serializing classes.
/// since the data is cached statically, we lock down access to it.
/// </SecurityNote>
private class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private ClassDataContract _baseContract;
private List<DataMember> _members;
private MethodInfo _onSerializing, _onSerialized;
private MethodInfo _onDeserializing, _onDeserialized;
#if !NET_NATIVE
private DataContractDictionary _knownDataContracts;
private bool _isKnownTypeAttributeChecked;
#endif
private bool _isMethodChecked;
/// <SecurityNote>
/// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and hasDataContract
/// </SecurityNote>
private bool _isNonAttributedType;
/// <SecurityNote>
/// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and isNonAttributedType
/// </SecurityNote>
private bool _hasDataContract;
#if NET_NATIVE
private bool _hasExtensionData;
#endif
private bool _isScriptObject;
private XmlDictionaryString[] _childElementNamespaces;
private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate;
private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate;
public XmlDictionaryString[] ContractNamespaces;
public XmlDictionaryString[] MemberNames;
public XmlDictionaryString[] MemberNamespaces;
internal ClassDataContractCriticalHelper() : base()
{
}
internal ClassDataContractCriticalHelper(Type type) : base(type)
{
XmlQualifiedName stableName = GetStableNameAndSetHasDataContract(type);
if (type == Globals.TypeOfDBNull)
{
this.StableName = stableName;
_members = new List<DataMember>();
XmlDictionary dictionary = new XmlDictionary(2);
this.Name = dictionary.Add(StableName.Name);
this.Namespace = dictionary.Add(StableName.Namespace);
this.ContractNamespaces = this.MemberNames = this.MemberNamespaces = Array.Empty<XmlDictionaryString>();
EnsureMethodsImported();
return;
}
Type baseType = type.GetTypeInfo().BaseType;
SetIsNonAttributedType(type);
SetKeyValuePairAdapterFlags(type);
this.IsValueType = type.GetTypeInfo().IsValueType;
if (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri)
{
DataContract baseContract = DataContract.GetDataContract(baseType);
if (baseContract is CollectionDataContract)
this.BaseContract = ((CollectionDataContract)baseContract).SharedTypeContract as ClassDataContract;
else
this.BaseContract = baseContract as ClassDataContract;
if (this.BaseContract != null && this.BaseContract.IsNonAttributedType && !_isNonAttributedType)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError
(new InvalidDataContractException(SR.Format(SR.AttributedTypesCannotInheritFromNonAttributedSerializableTypes,
DataContract.GetClrTypeFullName(type), DataContract.GetClrTypeFullName(baseType))));
}
}
else
this.BaseContract = null;
{
this.StableName = stableName;
ImportDataMembers();
XmlDictionary dictionary = new XmlDictionary(2 + Members.Count);
Name = dictionary.Add(StableName.Name);
Namespace = dictionary.Add(StableName.Namespace);
int baseMemberCount = 0;
int baseContractCount = 0;
if (BaseContract == null)
{
MemberNames = new XmlDictionaryString[Members.Count];
MemberNamespaces = new XmlDictionaryString[Members.Count];
ContractNamespaces = new XmlDictionaryString[1];
}
else
{
baseMemberCount = BaseContract.MemberNames.Length;
MemberNames = new XmlDictionaryString[Members.Count + baseMemberCount];
Array.Copy(BaseContract.MemberNames, 0, MemberNames, 0, baseMemberCount);
MemberNamespaces = new XmlDictionaryString[Members.Count + baseMemberCount];
Array.Copy(BaseContract.MemberNamespaces, 0, MemberNamespaces, 0, baseMemberCount);
baseContractCount = BaseContract.ContractNamespaces.Length;
ContractNamespaces = new XmlDictionaryString[1 + baseContractCount];
Array.Copy(BaseContract.ContractNamespaces, 0, ContractNamespaces, 0, baseContractCount);
}
ContractNamespaces[baseContractCount] = Namespace;
for (int i = 0; i < Members.Count; i++)
{
MemberNames[i + baseMemberCount] = dictionary.Add(Members[i].Name);
MemberNamespaces[i + baseMemberCount] = Namespace;
}
}
EnsureMethodsImported();
_isScriptObject = this.IsNonAttributedType &&
Globals.TypeOfScriptObject_IsAssignableFrom(this.UnderlyingType);
}
internal ClassDataContractCriticalHelper(Type type, XmlDictionaryString ns, string[] memberNames) : base(type)
{
this.StableName = new XmlQualifiedName(GetStableNameAndSetHasDataContract(type).Name, ns.Value);
ImportDataMembers();
XmlDictionary dictionary = new XmlDictionary(1 + Members.Count);
Name = dictionary.Add(StableName.Name);
Namespace = ns;
ContractNamespaces = new XmlDictionaryString[] { Namespace };
MemberNames = new XmlDictionaryString[Members.Count];
MemberNamespaces = new XmlDictionaryString[Members.Count];
for (int i = 0; i < Members.Count; i++)
{
Members[i].Name = memberNames[i];
MemberNames[i] = dictionary.Add(Members[i].Name);
MemberNamespaces[i] = Namespace;
}
EnsureMethodsImported();
}
private void EnsureIsReferenceImported(Type type)
{
DataContractAttribute dataContractAttribute;
bool isReference = false;
bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute);
if (BaseContract != null)
{
if (hasDataContractAttribute && dataContractAttribute.IsReferenceSetExplicitly)
{
bool baseIsReference = this.BaseContract.IsReference;
if ((baseIsReference && !dataContractAttribute.IsReference) ||
(!baseIsReference && dataContractAttribute.IsReference))
{
DataContract.ThrowInvalidDataContractException(
SR.Format(SR.InconsistentIsReference,
DataContract.GetClrTypeFullName(type),
dataContractAttribute.IsReference,
DataContract.GetClrTypeFullName(this.BaseContract.UnderlyingType),
this.BaseContract.IsReference),
type);
}
else
{
isReference = dataContractAttribute.IsReference;
}
}
else
{
isReference = this.BaseContract.IsReference;
}
}
else if (hasDataContractAttribute)
{
if (dataContractAttribute.IsReference)
isReference = dataContractAttribute.IsReference;
}
if (isReference && type.GetTypeInfo().IsValueType)
{
DataContract.ThrowInvalidDataContractException(
SR.Format(SR.ValueTypeCannotHaveIsReference,
DataContract.GetClrTypeFullName(type),
true,
false),
type);
return;
}
this.IsReference = isReference;
}
private void ImportDataMembers()
{
Type type = this.UnderlyingType;
EnsureIsReferenceImported(type);
List<DataMember> tempMembers = new List<DataMember>();
Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>();
MemberInfo[] memberInfos;
bool isPodSerializable = !_isNonAttributedType || IsKnownSerializableType(type);
if (!isPodSerializable)
{
memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
}
else
{
memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
for (int i = 0; i < memberInfos.Length; i++)
{
MemberInfo member = memberInfos[i];
if (HasDataContract)
{
object[] memberAttributes = member.GetCustomAttributes(typeof(DataMemberAttribute), false).ToArray();
if (memberAttributes != null && memberAttributes.Length > 0)
{
if (memberAttributes.Length > 1)
ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name));
DataMember memberContract = new DataMember(member);
if (member is PropertyInfo)
{
PropertyInfo property = (PropertyInfo)member;
MethodInfo getMethod = property.GetMethod;
if (getMethod != null && IsMethodOverriding(getMethod))
continue;
MethodInfo setMethod = property.SetMethod;
if (setMethod != null && IsMethodOverriding(setMethod))
continue;
if (getMethod == null)
ThrowInvalidDataContractException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property.Name));
if (setMethod == null)
{
if (!SetIfGetOnlyCollection(memberContract))
{
ThrowInvalidDataContractException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property.Name));
}
}
if (getMethod.GetParameters().Length > 0)
ThrowInvalidDataContractException(SR.Format(SR.IndexedPropertyCannotBeSerialized, property.DeclaringType, property.Name));
}
else if (!(member is FieldInfo))
ThrowInvalidDataContractException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(type), member.Name));
DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0];
if (memberAttribute.IsNameSetExplicitly)
{
if (memberAttribute.Name == null || memberAttribute.Name.Length == 0)
ThrowInvalidDataContractException(SR.Format(SR.InvalidDataMemberName, member.Name, DataContract.GetClrTypeFullName(type)));
memberContract.Name = memberAttribute.Name;
}
else
memberContract.Name = member.Name;
memberContract.Name = DataContract.EncodeLocalName(memberContract.Name);
memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
memberContract.IsRequired = memberAttribute.IsRequired;
if (memberAttribute.IsRequired && this.IsReference)
{
ThrowInvalidDataContractException(
SR.Format(SR.IsRequiredDataMemberOnIsReferenceDataContractType,
DataContract.GetClrTypeFullName(member.DeclaringType),
member.Name, true), type);
}
memberContract.EmitDefaultValue = memberAttribute.EmitDefaultValue;
memberContract.Order = memberAttribute.Order;
CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
}
}
else if (!isPodSerializable)
{
FieldInfo field = member as FieldInfo;
PropertyInfo property = member as PropertyInfo;
if ((field == null && property == null) || (field != null && field.IsInitOnly))
continue;
object[] memberAttributes = member.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).ToArray();
if (memberAttributes != null && memberAttributes.Length > 0)
{
if (memberAttributes.Length > 1)
ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name));
else
continue;
}
DataMember memberContract = new DataMember(member);
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0)
continue;
MethodInfo setMethod = property.SetMethod;
if (setMethod == null)
{
if (!SetIfGetOnlyCollection(memberContract))
continue;
}
else
{
if (!setMethod.IsPublic || IsMethodOverriding(setMethod))
continue;
}
}
memberContract.Name = DataContract.EncodeLocalName(member.Name);
memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
}
else
{
// [Serializible] and [NonSerialized] are deprecated on FxCore
// Try to mimic the behavior by allowing certain known types to go through
// POD types are fine also
FieldInfo field = member as FieldInfo;
if (CanSerializeMember(field))
{
DataMember memberContract = new DataMember(member);
memberContract.Name = DataContract.EncodeLocalName(member.Name);
object[] optionalFields = null;
if (optionalFields == null || optionalFields.Length == 0)
{
if (this.IsReference)
{
ThrowInvalidDataContractException(
SR.Format(SR.NonOptionalFieldMemberOnIsReferenceSerializableType,
DataContract.GetClrTypeFullName(member.DeclaringType),
member.Name, true), type);
}
memberContract.IsRequired = true;
}
memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
}
}
}
if (tempMembers.Count > 1)
tempMembers.Sort(DataMemberComparer.Singleton);
SetIfMembersHaveConflict(tempMembers);
Interlocked.MemoryBarrier();
_members = tempMembers;
}
private static bool CanSerializeMember(FieldInfo field)
{
return field != null && !ClassDataContract.IsNonSerializedMember(field.DeclaringType, field.Name);
}
private bool SetIfGetOnlyCollection(DataMember memberContract)
{
//OK to call IsCollection here since the use of surrogated collection types is not supported in get-only scenarios
if (CollectionDataContract.IsCollection(memberContract.MemberType, false /*isConstructorRequired*/) && !memberContract.MemberType.GetTypeInfo().IsValueType)
{
memberContract.IsGetOnlyCollection = true;
return true;
}
return false;
}
private void SetIfMembersHaveConflict(List<DataMember> members)
{
if (BaseContract == null)
return;
int baseTypeIndex = 0;
List<Member> membersInHierarchy = new List<Member>();
foreach (DataMember member in members)
{
membersInHierarchy.Add(new Member(member, this.StableName.Namespace, baseTypeIndex));
}
ClassDataContract currContract = BaseContract;
while (currContract != null)
{
baseTypeIndex++;
foreach (DataMember member in currContract.Members)
{
membersInHierarchy.Add(new Member(member, currContract.StableName.Namespace, baseTypeIndex));
}
currContract = currContract.BaseContract;
}
IComparer<Member> comparer = DataMemberConflictComparer.Singleton;
membersInHierarchy.Sort(comparer);
for (int i = 0; i < membersInHierarchy.Count - 1; i++)
{
int startIndex = i;
int endIndex = i;
bool hasConflictingType = false;
while (endIndex < membersInHierarchy.Count - 1
&& String.CompareOrdinal(membersInHierarchy[endIndex].member.Name, membersInHierarchy[endIndex + 1].member.Name) == 0
&& String.CompareOrdinal(membersInHierarchy[endIndex].ns, membersInHierarchy[endIndex + 1].ns) == 0)
{
membersInHierarchy[endIndex].member.ConflictingMember = membersInHierarchy[endIndex + 1].member;
if (!hasConflictingType)
{
if (membersInHierarchy[endIndex + 1].member.HasConflictingNameAndType)
{
hasConflictingType = true;
}
else
{
hasConflictingType = (membersInHierarchy[endIndex].member.MemberType != membersInHierarchy[endIndex + 1].member.MemberType);
}
}
endIndex++;
}
if (hasConflictingType)
{
for (int j = startIndex; j <= endIndex; j++)
{
membersInHierarchy[j].member.HasConflictingNameAndType = true;
}
}
i = endIndex + 1;
}
}
/// <SecurityNote>
/// Critical - sets the critical hasDataContract field
/// Safe - uses a trusted critical API (DataContract.GetStableName) to calculate the value
/// does not accept the value from the caller
/// </SecurityNote>
//CSD16748
//[SecuritySafeCritical]
private XmlQualifiedName GetStableNameAndSetHasDataContract(Type type)
{
return DataContract.GetStableName(type, out _hasDataContract);
}
/// <SecurityNote>
/// RequiresReview - marked SRR because callers may need to depend on isNonAttributedType for a security decision
/// isNonAttributedType must be calculated correctly
/// SetIsNonAttributedType should not be called before GetStableNameAndSetHasDataContract since it
/// is dependent on the correct calculation of hasDataContract
/// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value
/// </SecurityNote>
private void SetIsNonAttributedType(Type type)
{
_isNonAttributedType = !_hasDataContract && IsNonAttributedTypeValidForSerialization(type);
}
private static bool IsMethodOverriding(MethodInfo method)
{
return method.IsVirtual && ((method.Attributes & MethodAttributes.NewSlot) == 0);
}
internal void EnsureMethodsImported()
{
if (!_isMethodChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isMethodChecked)
{
Type type = this.UnderlyingType;
MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
for (int i = 0; i < methods.Length; i++)
{
MethodInfo method = methods[i];
Type prevAttributeType = null;
ParameterInfo[] parameters = method.GetParameters();
//THese attributes are cut from mscorlib.
if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializingAttribute, _onSerializing, ref prevAttributeType))
_onSerializing = method;
if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializedAttribute, _onSerialized, ref prevAttributeType))
_onSerialized = method;
if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializingAttribute, _onDeserializing, ref prevAttributeType))
_onDeserializing = method;
if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializedAttribute, _onDeserialized, ref prevAttributeType))
_onDeserialized = method;
}
Interlocked.MemoryBarrier();
_isMethodChecked = true;
}
}
}
}
private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType)
{
if (method.IsDefined(attributeType, false))
{
if (currentCallback != null)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType);
else if (prevAttributeType != null)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateAttribute, prevAttributeType, attributeType, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType);
else if (method.IsVirtual)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbacksCannotBeVirtualMethods, method, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType);
else
{
if (method.ReturnType != Globals.TypeOfVoid)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType);
if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfStreamingContext), method.DeclaringType);
prevAttributeType = attributeType;
}
return true;
}
return false;
}
internal ClassDataContract BaseContract
{
get { return _baseContract; }
set
{
_baseContract = value;
if (_baseContract != null && IsValueType)
ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName.Name, StableName.Namespace, _baseContract.StableName.Name, _baseContract.StableName.Namespace));
}
}
internal List<DataMember> Members
{
get { return _members; }
}
internal MethodInfo OnSerializing
{
get
{
EnsureMethodsImported();
return _onSerializing;
}
}
internal MethodInfo OnSerialized
{
get
{
EnsureMethodsImported();
return _onSerialized;
}
}
internal MethodInfo OnDeserializing
{
get
{
EnsureMethodsImported();
return _onDeserializing;
}
}
internal MethodInfo OnDeserialized
{
get
{
EnsureMethodsImported();
return _onDeserialized;
}
}
#if !NET_NATIVE
internal override DataContractDictionary KnownDataContracts
{
[SecurityCritical]
get
{
if (!_isKnownTypeAttributeChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isKnownTypeAttributeChecked)
{
_knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
Interlocked.MemoryBarrier();
_isKnownTypeAttributeChecked = true;
}
}
}
return _knownDataContracts;
}
[SecurityCritical]
set
{ _knownDataContracts = value; }
}
#endif
internal bool HasDataContract
{
get { return _hasDataContract; }
#if NET_NATIVE
set { _hasDataContract = value; }
#endif
}
#if NET_NATIVE
internal bool HasExtensionData
{
get { return _hasExtensionData; }
set { _hasExtensionData = value; }
}
#endif
internal bool IsNonAttributedType
{
get { return _isNonAttributedType; }
}
private void SetKeyValuePairAdapterFlags(Type type)
{
if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter)
{
_isKeyValuePairAdapter = true;
_keyValuePairGenericArguments = type.GetGenericArguments();
_keyValuePairCtorInfo = type.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfKeyValuePair.MakeGenericType(_keyValuePairGenericArguments) });
_getKeyValuePairMethodInfo = type.GetMethod("GetKeyValuePair", Globals.ScanAllMembers);
}
}
private bool _isKeyValuePairAdapter;
private Type[] _keyValuePairGenericArguments;
private ConstructorInfo _keyValuePairCtorInfo;
private MethodInfo _getKeyValuePairMethodInfo;
internal bool IsKeyValuePairAdapter
{
get { return _isKeyValuePairAdapter; }
}
internal bool IsScriptObject
{
get { return _isScriptObject; }
}
internal Type[] KeyValuePairGenericArguments
{
get { return _keyValuePairGenericArguments; }
}
internal ConstructorInfo KeyValuePairAdapterConstructorInfo
{
get { return _keyValuePairCtorInfo; }
}
internal MethodInfo GetKeyValuePairMethodInfo
{
get { return _getKeyValuePairMethodInfo; }
}
internal ConstructorInfo GetNonAttributedTypeConstructor()
{
if (!this.IsNonAttributedType)
return null;
Type type = UnderlyingType;
if (type.GetTypeInfo().IsValueType)
return null;
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>());
if (ctor == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type))));
return ctor;
}
internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate
{
get { return _xmlFormatWriterDelegate; }
set { _xmlFormatWriterDelegate = value; }
}
internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate
{
get { return _xmlFormatReaderDelegate; }
set { _xmlFormatReaderDelegate = value; }
}
public XmlDictionaryString[] ChildElementNamespaces
{
get { return _childElementNamespaces; }
set { _childElementNamespaces = value; }
}
internal struct Member
{
internal Member(DataMember member, string ns, int baseTypeIndex)
{
this.member = member;
this.ns = ns;
this.baseTypeIndex = baseTypeIndex;
}
internal DataMember member;
internal string ns;
internal int baseTypeIndex;
}
internal class DataMemberConflictComparer : IComparer<Member>
{
[SecuritySafeCritical]
public int Compare(Member x, Member y)
{
int nsCompare = String.CompareOrdinal(x.ns, y.ns);
if (nsCompare != 0)
return nsCompare;
int nameCompare = String.CompareOrdinal(x.member.Name, y.member.Name);
if (nameCompare != 0)
return nameCompare;
return x.baseTypeIndex - y.baseTypeIndex;
}
internal static DataMemberConflictComparer Singleton = new DataMemberConflictComparer();
}
#if NET_NATIVE
internal ClassDataContractCriticalHelper Clone()
{
ClassDataContractCriticalHelper clonedHelper = new ClassDataContractCriticalHelper(this.UnderlyingType);
clonedHelper._baseContract = this._baseContract;
clonedHelper._childElementNamespaces = this._childElementNamespaces;
clonedHelper.ContractNamespaces = this.ContractNamespaces;
clonedHelper._hasDataContract = this._hasDataContract;
clonedHelper._isMethodChecked = this._isMethodChecked;
clonedHelper._isNonAttributedType = this._isNonAttributedType;
clonedHelper.IsReference = this.IsReference;
clonedHelper.IsValueType = this.IsValueType;
clonedHelper.MemberNames = this.MemberNames;
clonedHelper.MemberNamespaces = this.MemberNamespaces;
clonedHelper._members = this._members;
clonedHelper.Name = this.Name;
clonedHelper.Namespace = this.Namespace;
clonedHelper._onDeserialized = this._onDeserialized;
clonedHelper._onDeserializing = this._onDeserializing;
clonedHelper._onSerialized = this._onSerialized;
clonedHelper._onSerializing = this._onSerializing;
clonedHelper.StableName = this.StableName;
clonedHelper.TopLevelElementName = this.TopLevelElementName;
clonedHelper.TopLevelElementNamespace = this.TopLevelElementNamespace;
clonedHelper._xmlFormatReaderDelegate = this._xmlFormatReaderDelegate;
clonedHelper._xmlFormatWriterDelegate = this._xmlFormatWriterDelegate;
return clonedHelper;
}
#endif
}
internal class DataMemberComparer : IComparer<DataMember>
{
public int Compare(DataMember x, DataMember y)
{
int orderCompare = x.Order - y.Order;
if (orderCompare != 0)
return orderCompare;
return String.CompareOrdinal(x.Name, y.Name);
}
internal static DataMemberComparer Singleton = new DataMemberComparer();
}
#if !NET_NATIVE
/// <summary>
/// Get object type for Xml/JsonFormmatReaderGenerator
/// </summary>
internal Type ObjectType
{
get
{
Type type = UnderlyingType;
if (type.GetTypeInfo().IsValueType && !IsNonAttributedType)
{
type = Globals.TypeOfValueType;
}
return type;
}
}
#endif
#if NET_NATIVE
internal ClassDataContract Clone()
{
ClassDataContract clonedDc = new ClassDataContract(this.UnderlyingType);
clonedDc._helper = _helper.Clone();
clonedDc.ContractNamespaces = this.ContractNamespaces;
clonedDc.ChildElementNamespaces = this.ChildElementNamespaces;
clonedDc.MemberNames = this.MemberNames;
clonedDc.MemberNamespaces = this.MemberNamespaces;
clonedDc.XmlFormatWriterDelegate = this.XmlFormatWriterDelegate;
clonedDc.XmlFormatReaderDelegate = this.XmlFormatReaderDelegate;
return clonedDc;
}
internal void UpdateNamespaceAndMembers(Type type, XmlDictionaryString ns, string[] memberNames)
{
this.StableName = new XmlQualifiedName(GetStableName(type).Name, ns.Value);
this.Namespace = ns;
XmlDictionary dictionary = new XmlDictionary(1 + memberNames.Length);
this.Name = dictionary.Add(StableName.Name);
this.Namespace = ns;
this.ContractNamespaces = new XmlDictionaryString[] { ns };
this.MemberNames = new XmlDictionaryString[memberNames.Length];
this.MemberNamespaces = new XmlDictionaryString[memberNames.Length];
for (int i = 0; i < memberNames.Length; i++)
{
this.MemberNames[i] = dictionary.Add(memberNames[i]);
this.MemberNamespaces[i] = ns;
}
}
#endif
}
}
| |
// 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 searchservice
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for DataSources.
/// </summary>
public static partial class DataSourcesExtensions
{
/// <summary>
/// Creates a new Azure Search datasource or updates a datasource if it already
/// exists.
/// <see href="https://msdn.microsoft.com/library/azure/dn946900.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to create or update.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static DataSource CreateOrUpdate(this IDataSources operations, string dataSourceName, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return operations.CreateOrUpdateAsync(dataSourceName, dataSource, searchRequestOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure Search datasource or updates a datasource if it already
/// exists.
/// <see href="https://msdn.microsoft.com/library/azure/dn946900.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to create or update.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSource> CreateOrUpdateAsync(this IDataSources operations, string dataSourceName, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(dataSourceName, dataSource, searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946881.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static void Delete(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
operations.DeleteAsync(dataSourceName, searchRequestOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946881.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(dataSourceName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Retrieves a datasource definition from Azure Search.
/// <see href="https://msdn.microsoft.com/library/azure/dn946893.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static DataSource Get(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return operations.GetAsync(dataSourceName, searchRequestOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves a datasource definition from Azure Search.
/// <see href="https://msdn.microsoft.com/library/azure/dn946893.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSourceName'>
/// The name of the datasource to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSource> GetAsync(this IDataSources operations, string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(dataSourceName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all datasources available for an Azure Search service.
/// <see href="https://msdn.microsoft.com/library/azure/dn946878.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static DataSourceListResult List(this IDataSources operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return operations.ListAsync(searchRequestOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all datasources available for an Azure Search service.
/// <see href="https://msdn.microsoft.com/library/azure/dn946878.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSourceListResult> ListAsync(this IDataSources operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946876.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static DataSource Create(this IDataSources operations, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return operations.CreateAsync(dataSource, searchRequestOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure Search datasource.
/// <see href="https://msdn.microsoft.com/library/azure/dn946876.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='dataSource'>
/// The definition of the datasource to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataSource> CreateAsync(this IDataSources operations, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(dataSource, searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using GrandTheftMultiplayer.Server;
using GrandTheftMultiplayer.Server.API;
using GrandTheftMultiplayer.Server.Constant;
using GrandTheftMultiplayer.Server.Elements;
using GrandTheftMultiplayer.Shared.Math;
/*
Gamemode Premise
You have 2 teams, one attacks one defends.
There's a time limit and a couple of objectives. Objectives are simple checkpoints
with a countdown attached. An attacker must 'capture' the objective to get it. Once an objective
has been captured, the spawnpoints are changed (optionally), and the attackers must capture the next one.
If the time runs out before the attackers capture all of the objectives, defenders win.
*/
public class Assault : Script
{
public Assault()
{
API.onResourceStart += Start;
API.onResourceStop += Stop;
API.onMapChange += MapChange;
API.onPlayerFinishedDownload += SpawnPlayer;
API.onPlayerRespawn += SpawnPlayer;
API.onUpdate += Update;
_rand = new Random();
}
/* EXPORTED */
public event ExportedEvent onRoundStart;
public event ExportedEvent onRoundEnd;
public event ExportedEvent onObjectiveCaptured;
public void invokeStart()
{
if (onRoundStart != null) onRoundStart.Invoke();
}
public void invokeEnd()
{
if (onRoundEnd != null) onRoundStart.Invoke();
}
public void invokeObjCaptured(int objective, List<Client> capturers)
{
if (onObjectiveCaptured != null) onObjectiveCaptured.Invoke(objective, capturers);
}
public Round CurrentRound;
public const int ATTACKER_TEAM = 1;
public const int DEFENDER_TEAM = 2;
private Random _rand;
private bool _lastContesting;
public void Start()
{
}
public void Stop()
{
foreach (var player in API.getAllPlayers())
{
player.team = 0;
}
}
public void MapChange(string name, XmlGroup map)
{
EndRound();
var round = new Round();
#region Objectives
foreach (var element in map.getElementsByType("objective"))
{
var obj = new Objective();
if (element.hasElementData("id"))
obj.Id = element.getElementData<int>("id");
obj.Position = new Vector3(element.getElementData<float>("posX"),
element.getElementData<float>("posY"),
element.getElementData<float>("posZ"));
if (element.hasElementData("range"))
obj.Range = element.getElementData<float>("range");
obj.name = element.getElementData<string>("name");
if (element.hasElementData("timer"))
obj.Timer = element.getElementData<int>("timer");
if (element.hasElementData("required"))
{
var listStr = element.getElementData<string>("required");
obj.RequiredObjectives =
listStr.Split(',').Select(id => int.Parse(id, CultureInfo.InvariantCulture)).ToList();
}
round.Objectives.Add(obj);
}
#endregion
#region Spawnpoints
foreach (var element in map.getElementsByType("spawnpoint"))
{
var sp = new Spawnpoint();
sp.Team = element.getElementData<int>("team");
sp.Heading = element.getElementData<float>("heading");
sp.Position = new Vector3(element.getElementData<float>("posX"),
element.getElementData<float>("posY"),
element.getElementData<float>("posZ"));
sp.Skins =
element.getElementData<string>("skins")
.Split(',')
.Select(s => API.pedNameToModel(s))
.ToArray();
var guns =
element.getElementData<string>("weapons")
.Split(',')
.Select(w => API.weaponNameToModel(w));
var ammos =
element.getElementData<string>("ammo")
.Split(',')
.Select(w => int.Parse(w, CultureInfo.InvariantCulture));
sp.Weapons = guns.ToArray();
sp.Ammo = ammos.ToArray();
if (element.hasElementData("objectives"))
{
var objectives =
element.getElementData<string>("objectives")
.Split(',')
.Select(w => int.Parse(w, CultureInfo.InvariantCulture));
sp.RequiredObjectives = objectives.ToArray();
}
round.Spawnpoints.Add(sp);
}
#endregion
StartRound(round);
}
public void SpawnPlayer(Client player)
{
if (CurrentRound == null) return;
if (player.team == 0)
player.team = _rand.Next(1, 3);
Spawnpoint[] availablePoints;
var groups =
CurrentRound.Spawnpoints.Where(
sp =>
sp.Team == player.team &&
(sp.RequiredObjectives.Length == 0 || AreAllObjectivesMet(sp.RequiredObjectives)))
.GroupBy(sp => sp.RequiredObjectives.Sum());
var max = groups.Max(grp => grp.Key);
availablePoints = groups.First(grp => grp.Key == max).ToArray();
var spawnpoint = availablePoints[_rand.Next(availablePoints.Length)];
player.health = 100;
player.armor = 0;
player.removeAllWeapons();
player.setSkin(spawnpoint.Skins[_rand.Next(spawnpoint.Skins.Length)]);
for (int i = 0; i < spawnpoint.Weapons.Length; i++)
{
player.giveWeapon(spawnpoint.Weapons[i], spawnpoint.Ammo[i], true, true);
}
player.team = spawnpoint.Team;
player.position = spawnpoint.Position;
player.rotation = new Vector3(0, 0, spawnpoint.Heading);
if (player.team == ATTACKER_TEAM)
{
API.triggerClientEvent(player, "display_subtitle", "Attack the ~r~objectives~w~!", 120000);
player.nametagColor = new Color(209, 25, 25);
}
else
{
API.triggerClientEvent(player, "display_subtitle", "Defend the ~b~objectives~w~!", 120000);
player.nametagColor = new Color(101, 186, 214);
}
}
public bool AreAllObjectivesMet(int[] objectives)
{
return objectives.All(
obj =>
CurrentRound.Objectives.Any(o => o.Id == obj) &&
CurrentRound.Objectives.First(o => o.Id == obj).Captured);
}
public void EndRound()
{
if (CurrentRound != null)
{
foreach (var ent in CurrentRound.Cleanup)
{
if (ent != null) API.deleteEntity(ent);
}
CurrentRound.Cleanup.Clear();
invokeEnd();
}
CurrentRound = null;
}
public void StartRound(Round round)
{
if (CurrentRound != null) EndRound();
CurrentRound = round;
_lastContesting = false;
var players = API.getAllPlayers();
for (int i = players.Count - 1; i >= 0; i--)
{
players[i].team = _rand.Next(1, 3);
SpawnPlayer(players[i]);
}
foreach (var objective in round.Objectives)
{
if (objective.RequiredObjectives.Count > 0) continue;
CreateObjective(objective);
}
invokeStart();
API.consoleOutput("Starting new round!");
}
public void CreateObjective(Objective objective)
{
objective.Marker = API.createMarker(28, objective.Position - new Vector3(0, 0, 0), new Vector3(), new Vector3(),
new Vector3(objective.Range, objective.Range, 5f), 30, 255, 255, 255);
objective.Blip = API.createBlip(objective.Position);
objective.Blip.color = 1;
objective.TextLabel = API.createTextLabel("", objective.Position + new Vector3(0, 0, 1.5f), 30f, 1f);
foreach (var player in API.getAllPlayers())
{
if (player.team == ATTACKER_TEAM)
{
API.triggerClientEvent(player, "set_blip_color", objective.Blip.handle, 1);
API.triggerClientEvent(player, "set_marker_color", objective.Marker.handle, 240, 10, 10);
API.triggerClientEvent(player, "display_subtitle", "Attack the ~r~objectives~w~!", 120000);
}
else
{
API.triggerClientEvent(player, "set_blip_color", objective.Blip.handle, 67);
API.triggerClientEvent(player, "set_marker_color", objective.Marker.handle, 19, 201, 237);
API.triggerClientEvent(player, "display_subtitle", "Defend the ~b~objectives~w~!", 120000);
}
}
objective.Spawned = true;
CurrentRound.Cleanup.Add(objective.Marker);
CurrentRound.Cleanup.Add(objective.Blip);
}
public void SpawnRequiredCheckpoints()
{
foreach (var objective in CurrentRound.Objectives)
{
if (objective.Spawned) continue;
if (objective.RequiredObjectives.All(
obj =>
CurrentRound.Objectives.Any(o => o.Id == obj) &&
CurrentRound.Objectives.First(o => o.Id == obj).Captured))
{
CreateObjective(objective);
}
}
}
public void Update()
{
if (CurrentRound == null) return;
foreach (var objective in CurrentRound.Objectives)
{
if (objective.Captured || !objective.Spawned) continue;
if (objective.RequiredObjectives.Count > 0 &&
objective.RequiredObjectives.Any(
obj =>
CurrentRound.Objectives.Any(o => o.Id == obj) &&
!CurrentRound.Objectives.First(o => o.Id == obj).Captured))
{
continue;
}
var players = API.getAllPlayers();
int attackersOnObjective = 0;
int defendersOnObjective = 0;
List<Client> OnPoint = new List<Client>();
foreach (var player in players)
{
if (player.position.DistanceToSquared(objective.Position) > objective.Range*objective.Range)
continue;
OnPoint.Add(player);
if (player.team == ATTACKER_TEAM) attackersOnObjective++;
else defendersOnObjective++;
}
if (attackersOnObjective > 0 && defendersOnObjective == 0)
{
_lastContesting = false;
if (!objective.Active)
{
objective.Active = true;
objective.TimeLeft = objective.Timer;
objective.LastActiveUpdate = API.TickCount;
API.triggerClientEventForAll("display_subtitle", "Objective ~y~" + objective.name + "~w~ is being captured!", objective.Timer);
API.sendNativeToAllPlayers(Hash.SET_BLIP_FLASHES, objective.Blip, true);
API.triggerClientEventForAll("set_marker_color", objective.Marker.handle, 7, 219, 21);
API.triggerClientEventForAll("play_sound", "GTAO_FM_Events_Soundset", "Enter_1st");
}
objective.TimeLeft -= (int) (API.TickCount - objective.LastActiveUpdate);
objective.LastActiveUpdate = API.TickCount;
if (API.TickCount - objective.LastLabelUpdate > 1000)
{
objective.TextLabel.text = "~y~~h~" + objective.name + "~h~~w~~n~" + (1f - ((float) objective.TimeLeft/objective.Timer)).ToString("P");
objective.LastLabelUpdate = API.TickCount;
}
if (objective.TimeLeft < 0)
{
objective.Captured = true;
objective.Blip.delete();
objective.Marker.delete();
objective.TextLabel.delete();
API.triggerClientEventForAll("display_shard", "~y~" + objective.name + "~w~ captured!", 5000);
API.triggerClientEventForAll("play_sound", "HUD_MINI_GAME_SOUNDSET", "3_2_1");
API.delay(5000, true, () =>
{
API.triggerClientEventForAll("play_sound", "GTAO_FM_Events_Soundset", "Shard_Disappear");
});
SpawnRequiredCheckpoints();
if (CurrentRound.Objectives.All(o => o.Captured))
{
API.sendChatMessageToAll("The attackers have won!");
API.exported.mapcycler.endRound();
}
invokeObjCaptured(objective.Id,
players.Where(
p => p.position.DistanceToSquared(objective.Position) < objective.Range*objective.Range)
.ToList());
}
}
else if (attackersOnObjective > 0 && defendersOnObjective > 0)
{
objective.LastActiveUpdate = API.TickCount;
if (!_lastContesting)
{
API.triggerClientEventForAll("set_marker_color", objective.Marker.handle, 242, 238, 10);
foreach (var client in OnPoint)
{
API.triggerClientEvent(client, "play_sound", "DLC_HEIST_BIOLAB_PREP_HACKING_SOUNDS", "Hack_failed");
}
}
_lastContesting = true;
}
else if (objective.Active)
{
_lastContesting = false;
objective.Active = false;
objective.LastActiveUpdate = 0;
objective.TextLabel.text = "";
API.sendNativeToAllPlayers(Hash.SET_BLIP_FLASHES, objective.Blip, false);
API.triggerClientEventForAll("play_sound", "GTAO_FM_Events_Soundset", "Lose_1st");
foreach (var player in API.getAllPlayers())
{
if (player.team == ATTACKER_TEAM)
{
API.triggerClientEvent(player, "set_blip_color", objective.Blip.handle, 1);
API.triggerClientEvent(player, "set_marker_color", objective.Marker.handle, 240, 10, 10);
API.triggerClientEvent(player, "display_subtitle", "Attack the ~r~objectives~w~!", 120000);
}
else
{
API.triggerClientEvent(player, "set_blip_color", objective.Blip.handle, 67);
API.triggerClientEvent(player, "set_marker_color", objective.Marker.handle, 19, 201, 237);
API.triggerClientEvent(player, "display_subtitle", "Defend the ~b~objectives~w~!", 120000);
}
}
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using achihapi.ViewModels;
using System.Data;
using System.Data.SqlClient;
using achihapi.Utilities;
using Microsoft.AspNetCore.JsonPatch;
using System.Net;
using Microsoft.Extensions.Caching.Memory;
namespace achihapi.Controllers
{
[Produces("application/json")]
[Route("api/FinanceAssetBuyDocument")]
public class FinanceAssetBuyDocumentController : Controller
{
private IMemoryCache _cache;
public FinanceAssetBuyDocumentController(IMemoryCache cache)
{
_cache = cache;
}
// GET: api/FinanceAssetBuyDocument
[HttpGet]
[Authorize]
public IActionResult Get()
{
return BadRequest();
}
//// GET: api/FinanceAssetBuyDocument/5
//[HttpGet("{id}")]
//[Authorize]
//public async Task<IActionResult> Get(int id, [FromQuery]Int32 hid = 0)
//{
// if (hid <= 0)
// return BadRequest("Not HID inputted");
// String usrName = String.Empty;
// if (Startup.UnitTestMode)
// usrName = UnitTestUtility.UnitTestUser;
// else
// {
// var usrObj = HIHAPIUtility.GetUserClaim(this);
// usrName = usrObj.Value;
// }
// if (String.IsNullOrEmpty(usrName))
// return BadRequest("User cannot recognize");
// FinanceAssetDocumentUIViewModel vm = new FinanceAssetDocumentUIViewModel();
// SqlConnection conn = null;
// SqlCommand cmd = null;
// SqlDataReader reader = null;
// String queryString = "";
// String strErrMsg = "";
// HttpStatusCode errorCode = HttpStatusCode.OK;
// try
// {
// queryString = HIHDBUtility.getFinanceDocAssetQueryString(id, true, hid);
// using(conn = new SqlConnection(Startup.DBConnectionString))
// {
// await conn.OpenAsync();
// // Check Home assignment with current user
// try
// {
// HIHAPIUtility.CheckHIDAssignment(conn, hid, usrName);
// }
// catch (Exception)
// {
// errorCode = HttpStatusCode.BadRequest;
// throw;
// }
// cmd = new SqlCommand(queryString, conn);
// reader = cmd.ExecuteReader();
// if (!reader.HasRows)
// {
// errorCode = HttpStatusCode.NotFound;
// throw new Exception();
// }
// // Header
// while (reader.Read())
// {
// HIHDBUtility.FinDocHeader_DB2VM(reader, vm);
// }
// reader.NextResult();
// // Items
// while (reader.Read())
// {
// FinanceDocumentItemUIViewModel itemvm = new FinanceDocumentItemUIViewModel();
// HIHDBUtility.FinDocItem_DB2VM(reader, itemvm);
// vm.Items.Add(itemvm);
// }
// reader.NextResult();
// // Account
// while (reader.Read())
// {
// FinanceAccountUIViewModel vmAccount = new FinanceAccountUIViewModel();
// Int32 aidx = 0;
// aidx = HIHDBUtility.FinAccountHeader_DB2VM(reader, vmAccount, aidx);
// vmAccount.ExtraInfo_AS = new FinanceAccountExtASViewModel();
// HIHDBUtility.FinAccountAsset_DB2VM(reader, vmAccount.ExtraInfo_AS, aidx);
// vm.AccountVM = vmAccount;
// }
// reader.NextResult();
// // Tags
// if (reader.HasRows)
// {
// while (reader.Read())
// {
// Int32 itemID = reader.GetInt32(0);
// String sterm = reader.GetString(1);
// foreach (var vitem in vm.Items)
// {
// if (vitem.ItemID == itemID)
// {
// vitem.TagTerms.Add(sterm);
// }
// }
// }
// }
// }
// }
// catch (Exception exp)
// {
// System.Diagnostics.Debug.WriteLine(exp.Message);
// strErrMsg = exp.Message;
// if (errorCode == HttpStatusCode.OK)
// errorCode = HttpStatusCode.InternalServerError;
// }
// finally
// {
// if (reader != null)
// {
// reader.Dispose();
// reader = null;
// }
// if (cmd != null)
// {
// cmd.Dispose();
// cmd = null;
// }
// if (conn != null)
// {
// conn.Dispose();
// conn = null;
// }
// }
// if (errorCode != HttpStatusCode.OK)
// {
// switch (errorCode)
// {
// case HttpStatusCode.Unauthorized:
// return Unauthorized();
// case HttpStatusCode.NotFound:
// return NotFound();
// case HttpStatusCode.BadRequest:
// return BadRequest(strErrMsg);
// default:
// return StatusCode(500, strErrMsg);
// }
// }
// var setting = new Newtonsoft.Json.JsonSerializerSettings
// {
// DateFormatString = HIHAPIConstants.DateFormatPattern,
// ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
// };
// return new JsonResult(vm, setting);
//}
// POST: api/FinanceAssetBuyDocument
[HttpPost]
[Authorize]
public async Task<IActionResult> Post([FromBody]FinanceAssetBuyinDocViewModel vm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (vm == null || vm.accountAsset == null)
return BadRequest("No data is inputted");
if (vm.HID <= 0)
return BadRequest("Not HID inputted");
// Do basic checks
if (String.IsNullOrEmpty(vm.TranCurr) || String.IsNullOrEmpty(vm.accountAsset.Name)
|| (vm.IsLegacy.HasValue && vm.IsLegacy.Value && vm.Items.Count > 0)
|| ((!vm.IsLegacy.HasValue || (vm.IsLegacy.HasValue && !vm.IsLegacy.Value)) && vm.Items.Count <= 0)
)
return BadRequest("Invalid input data");
foreach(var di in vm.Items)
{
if (di.TranAmount == 0 || di.AccountID <= 0 || di.TranType <= 0 || (di.ControlCenterID <= 0 && di.OrderID <= 0))
return BadRequest("Invalid input data in items!");
}
String usrName = String.Empty;
if (Startup.UnitTestMode)
usrName = UnitTestUtility.UnitTestUser;
else
{
var usrObj = HIHAPIUtility.GetUserClaim(this);
usrName = usrObj.Value;
}
if (String.IsNullOrEmpty(usrName))
return BadRequest("User cannot recognize");
// Construct the Account
var vmAccount = new FinanceAccountViewModel();
vmAccount.HID = vm.HID;
vmAccount.Name = vm.accountAsset.Name;
vmAccount.Status = FinanceAccountStatus.Normal;
vmAccount.CtgyID = FinanceAccountCtgyViewModel.AccountCategory_Asset;
vmAccount.ExtraInfo_AS = new FinanceAccountExtASViewModel();
vmAccount.Owner = vm.AccountOwner;
vmAccount.Comment = vm.accountAsset.Name;
vmAccount.ExtraInfo_AS.Name = vm.accountAsset.Name;
vmAccount.ExtraInfo_AS.Comment = vm.accountAsset.Comment;
vmAccount.ExtraInfo_AS.CategoryID = vm.accountAsset.CategoryID;
// Construct the Doc.
var vmFIDoc = new FinanceDocumentUIViewModel();
vmFIDoc.DocType = FinanceDocTypeViewModel.DocType_AssetBuyIn;
vmFIDoc.Desp = vm.Desp;
vmFIDoc.TranDate = vm.TranDate;
vmFIDoc.HID = vm.HID;
vmFIDoc.TranCurr = vm.TranCurr;
var maxItemID = 0;
if (vm.IsLegacy.HasValue && vm.IsLegacy.Value)
{
// Legacy account...
}
else
{
Decimal totalAmt = 0;
foreach (var di in vm.Items)
{
if (di.ItemID <= 0 || di.TranAmount == 0 || di.AccountID <= 0
|| (di.ControlCenterID <= 0 && di.OrderID <= 0))
return BadRequest("Invalid input data in items!");
// Todo: new check the tran. type is an expense!
totalAmt += di.TranAmount;
vmFIDoc.Items.Add(di);
if (maxItemID < di.ItemID)
maxItemID = di.ItemID;
}
if (totalAmt != vm.TranAmount)
return BadRequest("Amount is not even");
}
var nitem = new FinanceDocumentItemUIViewModel();
nitem.ItemID = ++maxItemID;
nitem.AccountID = -1;
nitem.TranAmount = vm.TranAmount;
nitem.Desp = vmFIDoc.Desp;
nitem.TranType = FinanceTranTypeViewModel.TranType_OpeningAsset;
if (vm.ControlCenterID.HasValue)
nitem.ControlCenterID = vm.ControlCenterID.Value;
if (vm.OrderID.HasValue)
nitem.OrderID = vm.OrderID.Value;
vmFIDoc.Items.Add(nitem);
// Update the database
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader reader = null;
SqlTransaction tran = null;
String queryString = "";
Int32 nNewDocID = -1;
String strErrMsg = "";
HttpStatusCode errorCode = HttpStatusCode.OK;
try
{
// Basic check again - document level
FinanceDocumentController.FinanceDocumentBasicCheck(vmFIDoc);
using (conn = new SqlConnection(Startup.DBConnectionString))
{
await conn.OpenAsync();
// Check Home assignment with current user
try
{
HIHAPIUtility.CheckHIDAssignment(conn, vm.HID, usrName);
}
catch (Exception)
{
errorCode = HttpStatusCode.BadRequest;
throw;
}
// Perfrom the doc. validation
await FinanceDocumentController.FinanceDocumentBasicValidationAsync(vmFIDoc, conn, -1);
// 0) Start the trasnaction for modifications
tran = conn.BeginTransaction();
// 1) craete the doc header => nNewDocID
queryString = HIHDBUtility.GetFinDocHeaderInsertString();
cmd = new SqlCommand(queryString, conn)
{
Transaction = tran
};
HIHDBUtility.BindFinDocHeaderInsertParameter(cmd, vmFIDoc, usrName);
SqlParameter idparam = cmd.Parameters.AddWithValue("@Identity", SqlDbType.Int);
idparam.Direction = ParameterDirection.Output;
Int32 nRst = await cmd.ExecuteNonQueryAsync();
nNewDocID = (Int32)idparam.Value;
vmFIDoc.ID = nNewDocID;
cmd.Dispose();
cmd = null;
// 2), create the new account => nNewAccountID
queryString = HIHDBUtility.GetFinanceAccountHeaderInsertString();
cmd = new SqlCommand(queryString, conn)
{
Transaction = tran
};
HIHDBUtility.BindFinAccountInsertParameter(cmd, vmAccount, usrName);
SqlParameter idparam2 = cmd.Parameters.AddWithValue("@Identity", SqlDbType.Int);
idparam2.Direction = ParameterDirection.Output;
nRst = await cmd.ExecuteNonQueryAsync();
vmAccount.ID = (Int32)idparam2.Value;
cmd.Dispose();
cmd = null;
// 3) create the Asset part of account
vmAccount.ExtraInfo_AS.AccountID = vmAccount.ID;
vmAccount.ExtraInfo_AS.RefDocForBuy = nNewDocID;
queryString = HIHDBUtility.GetFinanceAccountAssetInsertString();
cmd = new SqlCommand(queryString, conn)
{
Transaction = tran
};
HIHDBUtility.BindFinAccountAssetInsertParameter(cmd, vmAccount.ExtraInfo_AS);
nRst = await cmd.ExecuteNonQueryAsync();
cmd.Dispose();
cmd = null;
// 4) create the doc items
foreach (FinanceDocumentItemUIViewModel ivm in vmFIDoc.Items)
{
if (ivm.AccountID == -1)
ivm.AccountID = vmAccount.ID;
queryString = HIHDBUtility.GetFinDocItemInsertString();
cmd = new SqlCommand(queryString, conn)
{
Transaction = tran
};
HIHDBUtility.BindFinDocItemInsertParameter(cmd, ivm, nNewDocID);
await cmd.ExecuteNonQueryAsync();
cmd.Dispose();
cmd = null;
// Tags
if (ivm.TagTerms.Count > 0)
{
// Create tags
foreach (var term in ivm.TagTerms)
{
queryString = HIHDBUtility.GetTagInsertString();
cmd = new SqlCommand(queryString, conn, tran);
HIHDBUtility.BindTagInsertParameter(cmd, vm.HID, HIHTagTypeEnum.FinanceDocumentItem, nNewDocID, term, ivm.ItemID);
await cmd.ExecuteNonQueryAsync();
cmd.Dispose();
cmd = null;
}
}
}
// 5) Do the commit
tran.Commit();
// Update the buffer
// Account List
try
{
var cacheKey = String.Format(CacheKeys.FinAccountList, vm.HID, null);
this._cache.Remove(cacheKey);
}
catch (Exception)
{
// Do nothing here.
}
// B.S.
try
{
var cacheKey = String.Format(CacheKeys.FinReportBS, vm.HID);
this._cache.Remove(cacheKey);
}
catch (Exception)
{
// Do nothing here.
}
}
}
catch (Exception exp)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine(exp.Message);
#endif
strErrMsg = exp.Message;
if (errorCode == HttpStatusCode.OK)
errorCode = HttpStatusCode.InternalServerError;
if (tran != null)
tran.Rollback();
}
finally
{
if (tran != null)
{
tran.Dispose();
tran = null;
}
if (reader != null)
{
reader.Dispose();
reader = null;
}
if (cmd != null)
{
cmd.Dispose();
cmd = null;
}
if (conn != null)
{
conn.Dispose();
conn = null;
}
}
if (errorCode != HttpStatusCode.OK)
{
switch (errorCode)
{
case HttpStatusCode.Unauthorized:
return Unauthorized();
case HttpStatusCode.NotFound:
return NotFound();
case HttpStatusCode.BadRequest:
return BadRequest(strErrMsg);
default:
return StatusCode(500, strErrMsg);
}
}
return Ok(nNewDocID);
}
// PUT: api/FinanceAssetBuyDocument/5
[HttpPut("{id}")]
[Authorize]
public IActionResult Put([FromRoute]int id, [FromBody]string value)
{
return BadRequest();
}
// PATCH:
//[HttpPatch("{id}")]
//public async Task<IActionResult> Patch([FromRoute]int id, [FromQuery]int hid, [FromBody]JsonPatchDocument<FinanceAssetDocumentUIViewModel> patch)
//{
// if (patch == null || id <= 0 || patch.Operations.Count <= 0)
// return BadRequest("No data is inputted");
// if (hid <= 0)
// return BadRequest("No home is inputted");
// // Update the database
// SqlConnection conn = null;
// SqlCommand cmd = null;
// SqlDataReader reader = null;
// String queryString = "";
// String strErrMsg = "";
// Boolean headTranDateUpdate = false;
// DateTime? headTranDate = null;
// Boolean headDespUpdate = false;
// String headDesp = null;
// HttpStatusCode errorCode = HttpStatusCode.OK;
// // Check the inputs.
// // Allowed to change:
// // 1. Header: Transaction date, Desp;
// // 2. Item: Transaction amount, Desp, Control Center ID, Order ID,
// foreach (var oper in patch.Operations)
// {
// switch(oper.path)
// {
// case "/tranDate":
// headTranDateUpdate = true;
// headTranDate = (DateTime)oper.value;
// break;
// case "/desp":
// headDespUpdate = true;
// headDesp = (String) oper.value;
// break;
// default:
// return BadRequest("Unsupport field found");
// }
// }
// // User name
// String usrName = String.Empty;
// if (Startup.UnitTestMode)
// usrName = UnitTestUtility.UnitTestUser;
// else
// {
// var usrObj = HIHAPIUtility.GetUserClaim(this);
// usrName = usrObj.Value;
// }
// if (String.IsNullOrEmpty(usrName))
// return BadRequest("User cannot recognize");
// try
// {
// queryString = HIHDBUtility.GetFinDocHeaderExistCheckString(id);
// using(conn = new SqlConnection(Startup.DBConnectionString))
// {
// await conn.OpenAsync();
// // Check Home assignment with current user
// try
// {
// HIHAPIUtility.CheckHIDAssignment(conn, hid, usrName);
// }
// catch (Exception)
// {
// errorCode = HttpStatusCode.BadRequest;
// throw;
// }
// cmd = new SqlCommand(queryString, conn);
// reader = cmd.ExecuteReader();
// if (!reader.HasRows)
// {
// errorCode = HttpStatusCode.BadRequest;
// throw new Exception("Doc ID not exist");
// }
// else
// {
// reader.Dispose();
// reader = null;
// cmd.Dispose();
// cmd = null;
// //var vm = new FinanceAssetDocumentUIViewModel();
// //// Header
// //while (reader.Read())
// //{
// // HIHDBUtility.FinDocHeader_DB2VM(reader, vm);
// //}
// //reader.NextResult();
// //// Items
// //while (reader.Read())
// //{
// // FinanceDocumentItemUIViewModel itemvm = new FinanceDocumentItemUIViewModel();
// // HIHDBUtility.FinDocItem_DB2VM(reader, itemvm);
// // vm.Items.Add(itemvm);
// //}
// //reader.NextResult();
// //// Account
// //while (reader.Read())
// //{
// // FinanceAccountUIViewModel vmAccount = new FinanceAccountUIViewModel();
// // Int32 aidx = 0;
// // aidx = HIHDBUtility.FinAccountHeader_DB2VM(reader, vmAccount, aidx);
// // vmAccount.ExtraInfo_AS = new FinanceAccountExtASViewModel();
// // HIHDBUtility.FinAccountAsset_DB2VM(reader, vmAccount.ExtraInfo_AS, aidx);
// // vm.AccountVM = vmAccount;
// //}
// //reader.NextResult();
// //reader.Dispose();
// //reader = null;
// //cmd.Dispose();
// //cmd = null;
// //// Now go ahead for the update
// ////var patched = vm.Copy();
// //patch.ApplyTo(vm, ModelState);
// //if (!ModelState.IsValid)
// //{
// // return new BadRequestObjectResult(ModelState);
// //}
// // Optimized logic go ahead
// if (headTranDateUpdate || headDespUpdate)
// {
// queryString = HIHDBUtility.GetFinDocHeader_PatchString(headTranDateUpdate, headDespUpdate);
// cmd = new SqlCommand(queryString, conn);
// if (headTranDateUpdate)
// cmd.Parameters.AddWithValue("@TRANDATE", headTranDate);
// if (headDespUpdate)
// cmd.Parameters.AddWithValue("@DESP", headDesp);
// cmd.Parameters.AddWithValue("@UPDATEDAT", DateTime.Now);
// cmd.Parameters.AddWithValue("@UPDATEDBY", usrName);
// cmd.Parameters.AddWithValue("@ID", id);
// await cmd.ExecuteNonQueryAsync();
// }
// }
// }
// }
// catch (Exception exp)
// {
// System.Diagnostics.Debug.WriteLine(exp.Message);
// strErrMsg = exp.Message;
// if (errorCode == HttpStatusCode.OK)
// errorCode = HttpStatusCode.InternalServerError;
// }
// finally
// {
// if (reader != null)
// {
// reader.Dispose();
// reader = null;
// }
// if (cmd != null)
// {
// cmd.Dispose();
// cmd = null;
// }
// if (conn != null)
// {
// conn.Dispose();
// conn = null;
// }
// }
// if (errorCode != HttpStatusCode.OK)
// {
// switch (errorCode)
// {
// case HttpStatusCode.Unauthorized:
// return Unauthorized();
// case HttpStatusCode.NotFound:
// return NotFound();
// case HttpStatusCode.BadRequest:
// return BadRequest(strErrMsg);
// default:
// return StatusCode(500, strErrMsg);
// }
// }
// return Ok();
//}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
[Authorize]
public IActionResult Delete([FromRoute]int id)
{
return BadRequest();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Json5.Parsing
{
/// <summary>
/// Converts a stream of JSON5 tokens into a <see cref="Json5Value"/>.
/// </summary>
class Json5Parser
{
private Json5Lexer lexer;
private State state;
private Json5Value root;
private Stack<Json5Container> stack;
private Json5Container currentContainer;
private bool parsed = false;
/// <summary>
/// Constructs a new <see cref="Json5Parser"/> using a<see cref="TextReader"/>.
/// </summary>
/// <param name="reader">The reader that reads JSON5 text.</param>
public Json5Parser(TextReader reader)
{
this.lexer = new Json5Lexer(reader);
}
/// <summary>
/// Parses and returns a <see cref="Json5Value"/>.
/// </summary>
/// <returns>A <see cref="Json5Value"/>.</returns>
public Json5Value Parse()
{
if (this.parsed)
throw new InvalidOperationException("A Json5Parser may only be used once.");
this.state = State.Value;
this.root = null;
this.stack = new Stack<Json5Container>();
this.currentContainer = null;
this.parsed = true;
string key = null;
start:
Json5Token token = this.lexer.Read();
switch (this.state)
{
case State.Value:
switch (token.Type)
{
case Json5TokenType.String:
this.Add(new Json5String(token.String), key);
goto start;
case Json5TokenType.Number:
this.Add(new Json5Number(token.Number), key);
goto start;
case Json5TokenType.Punctuator:
switch (token.Character)
{
case '[':
this.Add(new Json5Array(), key);
goto start;
case '{':
this.Add(new Json5Object(), key);
goto start;
}
throw UnexpectedToken(token);
case Json5TokenType.Identifier:
// Since these are literal tokens, check token.Input
// instead of token.String. Whereas `true` and `\x74rue`
// are both valid identifiers that represent the same
// thing, only `true` is a boolean literal.
switch (token.Input)
{
case "true":
this.Add(new Json5Boolean(true), key);
goto start;
case "false":
this.Add(new Json5Boolean(false), key);
goto start;
case "null":
this.Add(Json5Value.Null, key);
goto start;
case "Infinity":
this.Add(new Json5Number(double.PositiveInfinity), key);
goto start;
case "NaN":
this.Add(new Json5Number(double.NaN), key);
goto start;
}
break;
}
break;
case State.BeforeArrayElement:
if (token.Type == Json5TokenType.Punctuator && token.Character == ']')
{
this.Pop();
goto start;
}
this.state = State.Value;
goto case State.Value;
case State.AfterArrayElement:
if (token.Type == Json5TokenType.Punctuator)
{
switch (token.Character)
{
case ',':
this.state = State.BeforeArrayElement;
goto start;
case ']':
this.Pop();
goto start;
}
}
break;
case State.BeforeObjectKey:
switch (token.Type)
{
case Json5TokenType.Punctuator:
if (token.Character == '}')
{
this.Pop();
goto start;
}
break;
case Json5TokenType.Identifier:
case Json5TokenType.String:
// All identifiers are valid as keys
// even if they are literals like
// `true`, `null`, or `Infinity`.
key = token.String;
this.state = State.AfterObjectKey;
goto start;
}
break;
case State.AfterObjectKey:
if (token.Type != Json5TokenType.Punctuator || token.Character != ':')
break;
this.state = State.Value;
goto start;
case State.AfterObjectValue:
if (token.Type == Json5TokenType.Punctuator)
{
switch (token.Character)
{
case ',':
this.state = State.BeforeObjectKey;
goto start;
case '}':
this.Pop();
goto start;
}
}
break;
case State.End:
if (token.Type == Json5TokenType.Eof)
return this.root;
break;
}
throw UnexpectedToken(token);
//throw new Exception("Invalid tree state.");
}
/// <summary>
/// Pushes a container onto the stack of open containers.
/// </summary>
/// <param name="container">The container to push onto the stack of open containers.</param>
/// <remarks>This also sets the current container and changes the state of the parser if appropriate.</remarks>
void Push(Json5Container container)
{
//if(this.root == null)
// this.root = container;
this.stack.Push(container);
this.currentContainer = container;
if (this.currentContainer is Json5Array)
this.state = State.BeforeArrayElement;
else
this.state = State.BeforeObjectKey;
}
/// <summary>
/// Pops a container off the stack of open containers, sets the current container, and resets the state of the
/// parser.
/// </summary>
/// <remarks>This also sets the current container and resets the state of the parser.</remarks>
void Pop()
{
this.stack.Pop();
this.currentContainer = this.stack.LastOrDefault();
this.ResetState();
}
/// <summary>
/// Adds a value to the current container, and uses the given key if the current container is an object.
/// </summary>
/// <param name="value">The value to add to the current container.</param>
/// <param name="key">The key to use if the current container is an object.</param>
/// <remarks>This also pushes <paramref name="value"/> onto the stack of open containers if
/// <paramref name="value"/> is a container; otherwise, it reset the state of the parser.</remarks>
void Add(Json5Value value, string key)
{
if (this.root == null)
this.root = value;
if (this.currentContainer is Json5Array)
((Json5Array)this.currentContainer).Add(value);
else if (this.currentContainer is Json5Object)
((Json5Object)this.currentContainer)[key] = value;
if (value is Json5Container)
this.Push((Json5Container)value);
else
this.ResetState();
}
/// <summary>
/// Resets the state of the parser based on the current container.
/// </summary>
void ResetState()
{
if (this.currentContainer == null)
this.state = State.End;
else if (this.currentContainer is Json5Array)
this.state = State.AfterArrayElement;
else
this.state = State.AfterObjectValue;
}
/// <summary>
/// Returns a <see cref="SyntaxError"/> for an unexpected token.
/// </summary>
/// <param name="token">The unexpected token.</param>
/// <returns>A <see cref="SyntaxError"/> for <paramref name="token"/>.</returns>
Exception UnexpectedToken(Json5Token token)
{
if (token.Type == Json5TokenType.Eof)
return new Json5UnexpectedEndOfInputException(token.Line, token.Column);
return new Json5UnexpectedInputException(token.Input, token.Line, token.Column);
}
/// <summary>
/// Represents a state that a <see cref="Json5Parser"/> is in.
/// </summary>
enum State
{
BeforeArrayElement,
AfterArrayElement,
BeforeObjectKey,
AfterObjectKey,
AfterObjectValue,
Value,
End,
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="LocalProxy.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Implements a data portal proxy to relay data portal</summary>
//-----------------------------------------------------------------------
using System;
using System.Threading;
using System.Threading.Tasks;
using Csla.Runtime;
using Csla.Server;
using Microsoft.Extensions.DependencyInjection;
namespace Csla.Channels.Local
{
/// <summary>
/// Implements a data portal proxy to relay data portal
/// calls to an application server hosted locally
/// in the client process and AppDomain.
/// </summary>
public class LocalProxy : DataPortalClient.IDataPortalProxy, IDisposable
{
/// <summary>
/// Creates an instance of the type
/// </summary>
/// <param name="applicationContext">ApplicationContext</param>
/// <param name="options">Options instance</param>
public LocalProxy(ApplicationContext applicationContext, LocalProxyOptions options)
{
ApplicationContext = applicationContext;
var provider = ApplicationContext.CurrentServiceProvider;
Options = options;
if (ApplicationContext.LogicalExecutionLocation == ApplicationContext.LogicalExecutionLocations.Client
&& ApplicationContext.IsAStatefulContextManager)
{
// create new DI scope and provider
_scope = ApplicationContext.CurrentServiceProvider.CreateScope();
provider = _scope.ServiceProvider;
// set runtime info to reflect that we're in a logical server-side
// data portal operation, so this "runtime" is stateless and
// we can't count on HttpContext
var runtimeInfo = provider.GetRequiredService<IRuntimeInfo>();
runtimeInfo.LocalProxyNewScopeExists = true;
}
_portal = provider.GetRequiredService<Server.IDataPortalServer>();
}
private ApplicationContext ApplicationContext { get; set; }
private readonly LocalProxyOptions Options;
private readonly IServiceScope _scope;
private readonly Server.IDataPortalServer _portal;
private bool disposedValue;
/// <summary>
/// Called by <see cref="DataPortal" /> to create a
/// new business object.
/// </summary>
/// <param name="objectType">Type of business object to create.</param>
/// <param name="criteria">Criteria object describing business object.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
public async Task<DataPortalResult> Create(
Type objectType, object criteria, DataPortalContext context, bool isSync)
{
if (isSync || ApplicationContext.LogicalExecutionLocation == ApplicationContext.LogicalExecutionLocations.Server)
{
return await _portal.Create(objectType, criteria, context, isSync);
}
else
{
if (!Options.FlowSynchronizationContext || SynchronizationContext.Current == null)
return await Task.Run(() => this._portal.Create(objectType, criteria, context, isSync));
else
return await await Task.Factory.StartNew(() => this._portal.Create(objectType, criteria, context, isSync),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
}
}
/// <summary>
/// Called by <see cref="DataPortal" /> to load an
/// existing business object.
/// </summary>
/// <param name="objectType">Type of business object to retrieve.</param>
/// <param name="criteria">Criteria object describing business object.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
public async Task<DataPortalResult> Fetch(Type objectType, object criteria, DataPortalContext context, bool isSync)
{
if (isSync || ApplicationContext.LogicalExecutionLocation == ApplicationContext.LogicalExecutionLocations.Server)
{
return await _portal.Fetch(objectType, criteria, context, isSync);
}
else
{
if (!Options.FlowSynchronizationContext || SynchronizationContext.Current == null)
return await Task.Run(() => this._portal.Fetch(objectType, criteria, context, isSync));
else
return await await Task.Factory.StartNew(() => this._portal.Fetch(objectType, criteria, context, isSync),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
}
}
/// <summary>
/// Called by <see cref="DataPortal" /> to update a
/// business object.
/// </summary>
/// <param name="obj">The business object to update.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
public async Task<DataPortalResult> Update(object obj, DataPortalContext context, bool isSync)
{
if (isSync || ApplicationContext.LogicalExecutionLocation == ApplicationContext.LogicalExecutionLocations.Server)
{
return await _portal.Update(obj, context, isSync);
}
else
{
if (!Options.FlowSynchronizationContext || SynchronizationContext.Current == null)
return await Task.Run(() => this._portal.Update(obj, context, isSync));
else
return await await Task.Factory.StartNew(() => this._portal.Update(obj, context, isSync),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
}
}
/// <summary>
/// Called by <see cref="DataPortal" /> to delete a
/// business object.
/// </summary>
/// <param name="objectType">Type of business object to create.</param>
/// <param name="criteria">Criteria object describing business object.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
public async Task<DataPortalResult> Delete(Type objectType, object criteria, DataPortalContext context, bool isSync)
{
if (isSync || ApplicationContext.LogicalExecutionLocation == ApplicationContext.LogicalExecutionLocations.Server)
{
return await _portal.Delete(objectType, criteria, context, isSync);
}
else
{
if (!Options.FlowSynchronizationContext || SynchronizationContext.Current == null)
return await Task.Run(() => this._portal.Delete(objectType, criteria, context, isSync));
else
return await await Task.Factory.StartNew(() => this._portal.Delete(objectType, criteria, context, isSync),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
}
}
/// <summary>
/// Gets a value indicating whether this proxy will invoke
/// a remote data portal server, or run the "server-side"
/// data portal in the caller's process and AppDomain.
/// </summary>
public bool IsServerRemote
{
get { return false; }
}
/// <summary>
/// Dispose current object
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
if (ApplicationContext.LogicalExecutionLocation == ApplicationContext.LogicalExecutionLocations.Client
&& ApplicationContext.IsAStatefulContextManager)
{
_scope?.Dispose();
}
}
disposedValue = true;
}
}
/// <summary>
/// Dispose current object
/// </summary>
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Research.CodeAnalysis;
using Microsoft.Research.CodeAnalysis.Caching.Models;
using Microsoft.Research.DataStructures;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.CodeAnalysis.Caching
{
#if false
class MemoryCacheDataAccessor : EntityCacheDataAccessor<MemMethodModel, MemCachingMetadata, MemAssemblyInfo, MemAssemblyBinding, MemoryClousotCacheEntities>
{
private readonly MemoryClousotCacheEntities persistedClousotCache;
private readonly object LockAssemblyInfoes = new object();
private readonly object LockMethods = new object();
public MemoryCacheDataAccessor(Dictionary<string, byte[]> metadataForCreation)
: base(Int32.MaxValue, new CacheVersionParameters { SetBaseLine = false, Version = 0 })
{
this.persistedClousotCache = new MemoryClousotCacheEntities();
this.persistedClousotCache.cachingMetadatas.AddRange(metadataForCreation.Select(md => new MemCachingMetadata() { Key = md.Key, Value = md.Value }));
}
protected override MemoryClousotCacheEntities CreateClousotCacheEntities(bool silent) { return this.persistedClousotCache; }
public override bool IsValid { get { return true; } }
public override void Clear()
{
lock (this.LockMethods)
this.persistedClousotCache.methodModels.Clear();
lock (this.LockAssemblyInfoes)
this.persistedClousotCache.assemblyInfoes.Clear();
this.persistedClousotCache.cachingMetadatas.Clear();
}
public override bool TryGetMethodModelForHash(ByteArray hash, out IMethodModel result)
{
lock (this.LockMethods)
return base.TryGetMethodModelForHash(hash, out result);
}
public override bool TryGetMethodModelForName(string name, out IMethodModel result)
{
lock (this.LockMethods)
return base.TryGetMethodModelForName(name, out result);
}
public override void AddAssemblyBinding(Guid assemblyGuid, IMethodModel methodModel)
{
lock (this.LockMethods)
base.AddAssemblyBinding(assemblyGuid, methodModel);
}
public override void AddAssemblyInfo(string assemblyName, Guid assemblyGuid)
{
lock (this.LockAssemblyInfoes)
base.AddAssemblyInfo(assemblyName, assemblyGuid);
}
public override void TryAddMethodModel(IMethodModel methodModel, ByteArray methodId)
{
lock (this.LockMethods)
base.TryAddMethodModel(methodModel, methodId);
}
public override void TrySaveChanges(bool now = false) {; }
}
class UnclearableMemoryCacheDataAccessor : MemoryCacheDataAccessor
{
public UnclearableMemoryCacheDataAccessor(Dictionary<string, byte[]> metadata)
: base(metadata)
{ }
public override void Clear() { }
}
#endif
class SliceId : ISliceId
{
private static readonly object Lock = new object();
private static int idgen;
private readonly int id;
private readonly string dll;
public SliceId(string dll)
{
lock (Lock)
this.id = ++idgen;
this.dll = dll;
}
public int Id { get { return this.id; } }
public string Dll { get { return this.dll; } }
public override int GetHashCode() { return this.id; }
public override string ToString() { return String.Format("{0}:{1}", this.id, this.dll); }
public override bool Equals(object obj)
{
return this.Equals(obj as SliceId);
}
public bool Equals(ISliceId other)
{
return other != null && this.id == other.Id;
}
}
class SliceHash : ByteArray, ISliceHash
{
public SliceHash(byte[] hash)
: base(hash)
{ }
public ByteArray Hash { get { return this; } }
public bool Equals(ISliceHash other) { return other != null && this.Hash.Equals(other.Hash); }
}
// TODO: make the SliceDataAccessor into a DB to save memory
class SliceDataAccessor : IDB
{
// TODO: do no act like everything is already know, because the DB can be accessed while the slices are still being built
private static readonly ISliceId[] EmptySliceIdArray = new ISliceId[0];
// Locks for the parallel cases
private readonly object LockCacheAccessor = new Object();
private readonly object LockDependencesCache = new Object();
private readonly object LockComputed = new Object();
private readonly IClousotCacheFactory[] cacheDataAccessorFactories; // Our standard DB
private IClousotCache cacheAccessor;
private readonly Dictionary<ISliceId, SliceDefinition> slices = new Dictionary<ISliceId, SliceDefinition>();
private readonly Dictionary<MethodId, ISliceId> sliceOfMethod = new Dictionary<MethodId, ISliceId>();
private readonly Dictionary<ISliceId, IEnumerable<ISliceId>> dependencesCache = new Dictionary<ISliceId, IEnumerable<ISliceId>>();
private readonly Dictionary<ISliceId, IEnumerable<ISliceId>> callersCache = new Dictionary<ISliceId, IEnumerable<ISliceId>>();
private readonly Set<Pair<ISliceId, ISliceHash>> computed = new Set<Pair<ISliceId, ISliceHash>>();
public SliceDataAccessor(IClousotCacheFactory[] cacheDataAccessorFactories)
{
this.cacheDataAccessorFactories = cacheDataAccessorFactories;
}
public ISliceHash ComputeSliceHash(ISliceId sliceId, DateTime t)
{
// We do not consider the methods in the same type at the moment
SliceDefinition sliceDef;
// If we do not know the slice, we just return null
if (!this.slices.TryGetValue(sliceId, out sliceDef))
return null;
// TODO: wire the hashing option
using (var tw = new HashWriter(false))
{
foreach (var methodId in sliceDef.Dependencies)
{
tw.Write(methodId);
tw.Write(':');
var methodHash = this.GetHashForDate(methodId, t, false);
Method methodModel;
if (methodHash == null || !this.TryGetMethodModelForHash(methodHash, out methodModel))
tw.WriteLine("<null>");
else
tw.WriteLine(this.GetResultHash(methodModel));
}
return new SliceHash(tw.GetHash());
}
}
public ByteArray GetResultHash(Method methodModel)
{
Contract.Requires(methodModel != null);
// Put in this hash only what the analysis of other methods will rely on (i.e. time stats would not be a good idea)
return new ByteArray(methodModel.InferredExprHash, methodModel.PureParametersMask, methodModel.Timeout);
}
// Get the latest just before or after the time t
private ByteArray GetHashForDate(MethodId methodId, DateTime t, bool afterT)
{
if (this.cacheAccessor == null)
return null;
return this.cacheAccessor.GetHashForDate(methodId, t, afterT);
}
private bool TryGetMethodModelForHash(ByteArray methodHash, out Method methodModel)
{
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out methodModel) != null);
if (this.cacheAccessor == null)
{
methodModel = default(Method);
return false;
}
return this.cacheAccessor.TryGetMethodModelForHash(methodHash, out methodModel);
}
public bool AlreadyComputed(ISliceId sliceId, ISliceHash sliceHash)
{
lock (this.LockComputed)
return this.computed.Contains(Pair.For(sliceId, sliceHash));
}
public void MarkAsComputed(ISliceId sliceId, ISliceHash sliceHash)
{
lock (this.LockComputed)
this.computed.Add(Pair.For(sliceId, sliceHash));
}
public ISliceId RegisterSlice(SliceDefinition sliceDef)
{
var sliceId = new SliceId(sliceDef.Dll);
this.slices.Add(sliceId, sliceDef);
foreach (var h in sliceDef.Methods)
this.sliceOfMethod.Add(h, sliceId);
lock (this.LockDependencesCache)
this.dependencesCache.Clear(); // invalidate dependences because it can be based on outdated sliceOfMethod values
return sliceId;
}
public IEnumerable<ISliceId> Dependences(ISliceId sliceId)
{
IEnumerable<ISliceId> res;
lock (this.LockDependencesCache)
{
if (this.dependencesCache.TryGetValue(sliceId, out res))
{
return res;
}
}
SliceDefinition sliceDef;
if (!this.slices.TryGetValue(sliceId, out sliceDef))
{
return EmptySliceIdArray; // should not happen
}
var result = new Set<ISliceId>();
ISliceId depSliceId;
foreach (var m in sliceDef.Dependencies)
{
if (this.sliceOfMethod.TryGetValue(m, out depSliceId))
{
result.Add(depSliceId);
}
}
lock (this.LockDependencesCache)
{
var callers = ComputeCallersDependencies(sliceId);
result.AddRange(callers);
this.dependencesCache.Add(sliceId, result);
}
return result;
}
private IEnumerable<ISliceId> ComputeCallersDependencies(ISliceId sliceId)
{
Contract.Requires(sliceId != null);
lock (this.LockDependencesCache)
{
IEnumerable<ISliceId> cachedCallers;
if (this.callersCache.TryGetValue(sliceId, out cachedCallers))
{
return cachedCallers;
}
var result = new Set<ISliceId>();
// TODO: generalize to a set of methods?
var methodIdForSliceId = this.sliceOfMethod.Where(pair => pair.Value.Equals(sliceId)).Select(pair => pair.Key).FirstOrDefault();
if (methodIdForSliceId != null)
{
foreach (var slice in this.slices)
{
if (slice.Value.Dependencies.Contains(methodIdForSliceId))
{
// the slice depends on the method
result.Add(slice.Key);
}
}
}
this.callersCache.Add(sliceId, result);
return result;
}
}
public IEnumerable<ISliceId> SlicesForMethodsInTheSameType(ISliceId sliceId)
{
SliceDefinition sliceDefinition;
if(this.slices.TryGetValue(sliceId, out sliceDefinition))
{
foreach (var m in sliceDefinition.MethodsInTheSameType)
{
foreach (var slice in this.slices)
{
if (slice.Value.Methods.Contains(m))
{
Console.WriteLine("Scheduling slice: {0}", slice.Key);
yield return slice.Key;
break; // done with the methodId m;
}
}
}
}
}
public virtual IClousotCache Create(IClousotCacheOptions options)
{
if (this.cacheAccessor == null) // avoids locking if not necessary
{
lock (this.LockCacheAccessor)
if (this.cacheAccessor == null)
{
foreach (var factory in this.cacheDataAccessorFactories)
{
this.cacheAccessor = factory.Create(options);
//test the db connection
if (this.cacheAccessor != null && this.cacheAccessor.TestCache())
break;
this.cacheAccessor = null;
}
}
}
return new UndisposableCacheDataAccessor(this.cacheAccessor);
}
public void Dispose()
{
if (this.cacheAccessor != null)
{
this.cacheAccessor.Dispose();
this.cacheAccessor = null;
}
}
}
}
| |
//
// MRItemManager.cs
//
// Author:
// Steve Jakab <>
//
// Copyright (c) 2014 Steve Jakab
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using AssemblyCSharp;
namespace PortableRealm
{
public class MRItemManager
{
#region Properties
public static IDictionary<uint, MRItem> Items
{
get{
return msItems;
}
}
public static IDictionary<uint, MRWeapon> Weapons
{
get{
return msWeapons;
}
}
public static IDictionary<uint, MRArmor> Armor
{
get{
return msArmor;
}
}
public static IDictionary<uint, MRTreasure> Treasure
{
get{
return msTreasure;
}
}
public static IDictionary<uint, MRHorse> Horses
{
get{
return msHorses;
}
}
#endregion
#region Methods
public MRItemManager ()
{
try
{
TextAsset itemsList = (TextAsset)Resources.Load("Items");
StringBuilder jsonText = new StringBuilder(itemsList.text);
JSONObject jsonData = (JSONObject)JSONDecoder.CreateJSONValue(jsonText);
// parse the weapon data
JSONArray weaponsData = (JSONArray)jsonData["weapons"];
int count = weaponsData.Count;
for (int i = 0; i < count; ++i)
{
object[] weapons = JSONDecoder.DecodeObjects((JSONObject)weaponsData[i]);
if (weapons != null)
{
foreach (object weapon in weapons)
{
msItems.Add(((MRWeapon)weapon).Id, (MRWeapon)weapon);
msWeapons.Add(((MRWeapon)weapon).Id, (MRWeapon)weapon);
}
}
}
// parse the armor data
JSONArray armorData = (JSONArray)jsonData["armor"];
count = armorData.Count;
for (int i = 0; i < count; ++i)
{
object[] armor = JSONDecoder.DecodeObjects((JSONObject)armorData[i]);
if (armor != null)
{
foreach (object piece in armor)
{
msItems.Add(((MRArmor)piece).Id, (MRArmor)piece);
msArmor.Add(((MRArmor)piece).Id, (MRArmor)piece);
}
}
}
// parse the treasure data
JSONArray treasureData = (JSONArray)jsonData["treasure"];
count = treasureData.Count;
for (int i = 0; i < count; ++i)
{
object[] treasures = JSONDecoder.DecodeObjects((JSONObject)treasureData[i]);
if (treasures != null)
{
foreach (object treasure in treasures)
{
msItems.Add(((MRTreasure)treasure).Id, (MRTreasure)treasure);
msTreasure.Add(((MRTreasure)treasure).Id, (MRTreasure)treasure);
}
}
}
// parse the horse data
JSONArray horsesData = (JSONArray)jsonData["horses"];
count = horsesData.Count;
for (int i = 0; i < count; ++i)
{
object[] horses = JSONDecoder.DecodeObjects((JSONObject)horsesData[i]);
if (horses != null)
{
foreach (object horse in horses)
{
msItems.Add(((MRHorse)horse).Id, (MRHorse)horse);
msHorses.Add(((MRHorse)horse).Id, (MRHorse)horse);
}
}
}
}
catch (Exception err)
{
Debug.LogError("Error parsing items: " + err);
}
}
/// <summary>
/// Removes all items from their current stacks and set their start stack to null.
/// </summary>
public static void ResetItems()
{
foreach(MRItem item in msItems.Values)
{
if (item.Stack != null)
item.Stack.RemovePiece(item);
item.StartStack = null;
}
}
/// <summary>
/// Returns the item with a given id.
/// </summary>
/// <returns>The item.</returns>
/// <param name="id">Identifier.</param>
public static MRItem GetItem(uint id)
{
MRItem item;
if (msItems.TryGetValue(id, out item))
return item;
Debug.LogError("Request for unknown item id " + id);
return null;
}
/// <summary>
/// Returns a named weapon.
/// </summary>
/// <returns>The weapon, or null if none exists.</returns>
/// <param name="name">weapon name. This can be the first unique part of the name.</param>
/// <param name="index">optional weapon index, for non-unique weapons. Pass -1 to return any valid weapon.</param>
public static MRWeapon GetWeapon(string name, int index)
{
foreach (MRWeapon weapon in msWeapons.Values)
{
if (weapon.Name.StartsWith(name) && (index < 0 || weapon.Index == index))
return weapon;
}
return null;
}
/// <summary>
/// Returns a named armor.
/// </summary>
/// <returns>The armor, or null if none exists.</returns>
/// <param name="name">armor name. This can be the first unique part of the name.</param>
/// <param name="index">optional armor index, for non-unique armor. Pass -1 to return any valid armor.</param>
public static MRArmor GetArmor(string name, int index)
{
foreach (MRArmor armor in msArmor.Values)
{
if (armor.Name.StartsWith(name) && (index < 0 || armor.Index == index))
return armor;
}
return null;
}
/// <summary>
/// Returns a treasure with the given name.
/// </summary>
/// <returns>The treasure.</returns>
/// <param name="name">Name.</param>
public static MRTreasure GetTreasure(string name)
{
foreach (MRTreasure item in msTreasure.Values)
{
if (item.Name.Equals(name))
return item;
}
return null;
}
#endregion
#region Members
private static IDictionary<uint, MRItem> msItems = new Dictionary<uint, MRItem>();
private static IDictionary<uint, MRWeapon> msWeapons = new Dictionary<uint, MRWeapon>();
private static IDictionary<uint, MRArmor> msArmor = new Dictionary<uint, MRArmor>();
private static IDictionary<uint, MRTreasure> msTreasure = new Dictionary<uint, MRTreasure>();
private static IDictionary<uint, MRHorse> msHorses = new Dictionary<uint, MRHorse>();
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using FSLib = FSharp.Compiler.AbstractIL.Internal.Library;
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Threading;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{
internal class Transactional
{
/// Run 'stepWithEffect' followed by continuation 'k', but if the continuation later fails with
/// an exception, undo the original effect by running 'compensatingEffect'.
/// Note: if 'compensatingEffect' throws, it masks the original exception.
/// Note: This is a monadic bind where the first two arguments comprise M<A>.
public static B Try<A, B>(Func<A> stepWithEffect, Action<A> compensatingEffect, Func<A, B> k)
{
var stepCompleted = false;
var allOk = false;
A a = default(A);
try
{
a = stepWithEffect();
stepCompleted = true;
var r = k(a);
allOk = true;
return r;
}
finally
{
if (!allOk && stepCompleted)
{
compensatingEffect(a);
}
}
}
// if A == void, this is the overload
public static B Try<B>(Action stepWithEffect, Action compensatingEffect, Func<B> k)
{
return Try(
() => { stepWithEffect(); return 0; },
(int dummy) => { compensatingEffect(); },
(int dummy) => { return k(); });
}
// if A & B are both void, this is the overload
public static void Try(Action stepWithEffect, Action compensatingEffect, Action k)
{
Try(
() => { stepWithEffect(); return 0; },
(int dummy) => { compensatingEffect(); },
(int dummy) => { k(); return 0; });
}
}
[CLSCompliant(false)]
[ComVisible(true)]
public class FileNode : HierarchyNode
{
private static Dictionary<string, int> extensionIcons;
/// <summary>
/// overwrites of the generic hierarchyitem.
/// </summary>
[System.ComponentModel.BrowsableAttribute(false)]
public override string Caption
{
get
{
// Use LinkedIntoProjectAt property if available
string caption = this.ItemNode.GetMetadata(ProjectFileConstants.LinkedIntoProjectAt);
if (caption == null || caption.Length == 0)
{
// Otherwise use filename
caption = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
caption = Path.GetFileName(caption);
}
return caption;
}
}
public override int ImageIndex
{
get
{
// Check if the file is there.
if (!this.CanShowDefaultIcon())
{
return (int)ProjectNode.ImageName.MissingFile;
}
//Check for known extensions
int imageIndex;
string extension = System.IO.Path.GetExtension(this.FileName);
if ((string.IsNullOrEmpty(extension)) || (!extensionIcons.TryGetValue(extension, out imageIndex)))
{
// Missing or unknown extension; let the base class handle this case.
return base.ImageIndex;
}
// The file type is known and there is an image for it in the image list.
return imageIndex;
}
}
public override Guid ItemTypeGuid
{
get { return VSConstants.GUID_ItemType_PhysicalFile; }
}
public override int MenuCommandId
{
get { return VsMenus.IDM_VS_CTXT_ITEMNODE; }
}
public override string Url
{
get
{
string path = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
if (String.IsNullOrEmpty(path))
{
return String.Empty;
}
Url url;
if (Path.IsPathRooted(path))
{
// Use absolute path
url = new Microsoft.VisualStudio.Shell.Url(path);
}
else
{
// Path is relative, so make it relative to project path
url = new Url(this.ProjectMgr.BaseURI, path);
}
return url.AbsoluteUrl;
}
}
static FileNode()
{
// Build the dictionary with the mapping between some well known extensions
// and the index of the icons inside the standard image list.
extensionIcons = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
extensionIcons.Add(".aspx", (int)ProjectNode.ImageName.WebForm);
extensionIcons.Add(".asax", (int)ProjectNode.ImageName.GlobalApplicationClass);
extensionIcons.Add(".asmx", (int)ProjectNode.ImageName.WebService);
extensionIcons.Add(".ascx", (int)ProjectNode.ImageName.WebUserControl);
extensionIcons.Add(".asp", (int)ProjectNode.ImageName.ASPPage);
extensionIcons.Add(".config", (int)ProjectNode.ImageName.WebConfig);
extensionIcons.Add(".htm", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".html", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".css", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".xsl", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".vbs", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".js", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".wsf", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".txt", (int)ProjectNode.ImageName.TextFile);
extensionIcons.Add(".resx", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".rc", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".bmp", (int)ProjectNode.ImageName.Bitmap);
extensionIcons.Add(".ico", (int)ProjectNode.ImageName.Icon);
extensionIcons.Add(".gif", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".jpg", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".png", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".map", (int)ProjectNode.ImageName.ImageMap);
extensionIcons.Add(".wav", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".mid", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".midi", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".avi", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mov", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpeg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".cab", (int)ProjectNode.ImageName.CAB);
extensionIcons.Add(".jar", (int)ProjectNode.ImageName.JAR);
extensionIcons.Add(".xslt", (int)ProjectNode.ImageName.XSLTFile);
extensionIcons.Add(".xsd", (int)ProjectNode.ImageName.XMLSchema);
extensionIcons.Add(".xml", (int)ProjectNode.ImageName.XMLFile);
extensionIcons.Add(".pfx", (int)ProjectNode.ImageName.PFX);
extensionIcons.Add(".snk", (int)ProjectNode.ImageName.SNK);
}
/// <summary>
/// Constructor for the FileNode
/// </summary>
/// <param name="root">Root of the hierarchy</param>
/// <param name="element">Associated project element</param>
internal FileNode(ProjectNode root, ProjectElement element, uint? hierarchyId = null)
: base(root, element, hierarchyId)
{
if (this.ProjectMgr.NodeHasDesigner(this.ItemNode.GetMetadata(ProjectFileConstants.Include)))
{
this.HasDesigner = true;
}
}
public virtual string RelativeFilePath
{
get
{
return PackageUtilities.MakeRelativeIfRooted(this.Url, this.ProjectMgr.BaseURI);
}
}
public override NodeProperties CreatePropertiesObject()
{
return new FileNodeProperties(this);
}
public override object GetIconHandle(bool open)
{
int index = this.ImageIndex;
if (NoImage == index)
{
// There is no image for this file; let the base class handle this case.
return base.GetIconHandle(open);
}
// Return the handle for the image.
return this.ProjectMgr.ImageHandler.GetIconHandle(index);
}
/// <summary>
/// Get an instance of the automation object for a FileNode
/// </summary>
/// <returns>An instance of the Automation.OAFileNode if succeeded</returns>
public override object GetAutomationObject()
{
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return null;
}
return new Automation.OAFileItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Renames a file node.
/// </summary>
/// <param name="label">The new name.</param>
/// <returns>An errorcode for failure or S_OK.</returns>
/// <exception cref="InvalidOperationException">if the file cannot be validated</exception>
/// <devremark>
/// We are going to throw instaed of showing messageboxes, since this method is called from various places where a dialog box does not make sense.
/// For example the FileNodeProperties are also calling this method. That should not show directly a messagebox.
/// Also the automation methods are also calling SetEditLabel
/// </devremark>
public override int SetEditLabel(string label)
{
// IMPORTANT NOTE: This code will be called when a parent folder is renamed. As such, it is
// expected that we can be called with a label which is the same as the current
// label and this should not be considered a NO-OP.
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return VSConstants.E_FAIL;
}
// Validate the filename.
if (String.IsNullOrEmpty(label))
{
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, CultureInfo.CurrentUICulture));
}
else if (label.Length > NativeMethods.MAX_PATH)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.PathTooLong, CultureInfo.CurrentUICulture), label));
}
else if (Utilities.IsFileNameInvalid(label))
{
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, CultureInfo.CurrentUICulture));
}
for (HierarchyNode n = this.Parent.FirstChild; n != null; n = n.NextSibling)
{
if (n != this && String.Compare(n.Caption, label, StringComparison.OrdinalIgnoreCase) == 0)
{
//A file or folder with the name '{0}' already exists on disk at this location. Please choose another name.
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileOrFolderAlreadyExists, CultureInfo.CurrentUICulture), label));
}
}
string fileName = Path.GetFileNameWithoutExtension(label);
// If there is no filename or it starts with a leading dot issue an error message and quit.
if (String.IsNullOrEmpty(fileName) || fileName[0] == '.')
{
throw new InvalidOperationException(SR.GetString(SR.FileNameCannotContainALeadingPeriod, CultureInfo.CurrentUICulture));
}
// Verify that the file extension is unchanged
string strRelPath = Path.GetFileName(this.ItemNode.GetMetadata(ProjectFileConstants.Include));
if (String.Compare(Path.GetExtension(strRelPath), Path.GetExtension(label), StringComparison.OrdinalIgnoreCase) != 0)
{
// Don't prompt if we are in automation function.
if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
{
// Prompt to confirm that they really want to change the extension of the file
string message = SR.GetString(SR.ConfirmExtensionChange, CultureInfo.CurrentUICulture, new string[] { label });
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Debug.Assert(shell != null, "Could not get the ui shell from the project");
if (shell == null)
{
return VSConstants.E_FAIL;
}
if (!PromptYesNoWithYesSelected(message, null, OLEMSGICON.OLEMSGICON_INFO, shell))
{
// The user cancelled the confirmation for changing the extension.
// Return S_OK in order not to show any extra dialog box
return VSConstants.S_OK;
}
}
}
// Build the relative path by looking at folder names above us as one scenarios
// where we get called is when a folder above us gets renamed (in which case our path is invalid)
HierarchyNode parent = this.Parent;
while (parent != null && (parent is FolderNode))
{
strRelPath = Path.Combine(parent.Caption, strRelPath);
parent = parent.Parent;
}
var result = SetEditLabel(label, strRelPath);
return result;
}
// Implementation of functionality from Microsoft.VisualStudio.Shell.VsShellUtilities.PromptYesNo
// Difference: Yes button is default
private static bool PromptYesNoWithYesSelected(string message, string title, OLEMSGICON icon, IVsUIShell uiShell)
{
Guid emptyGuid = Guid.Empty;
int result = 0;
#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs
ThreadHelper.Generic.Invoke(() =>
#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs
{
ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox(0u, ref emptyGuid, title, message, null, 0u, OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, icon, 0, out result));
});
return result == (int)NativeMethods.IDYES;
}
public override string GetMkDocument()
{
Debug.Assert(this.Url != null, "No url specified for this node");
return this.Url;
}
/// <summary>
/// Delete the item corresponding to the specified path from storage.
/// </summary>
/// <param name="path"></param>
public override void DeleteFromStorage(string path)
{
if (FSLib.Shim.FileSystem.SafeExists(path))
{
File.SetAttributes(path, FileAttributes.Normal); // make sure it's not readonly.
File.Delete(path);
}
}
/// <summary>
/// Rename the underlying document based on the change the user just made to the edit label.
/// </summary>
public int SetEditLabel(string label, string relativePath)
{
int returnValue = VSConstants.S_OK;
uint oldId = this.ID;
string strSavePath = Path.GetDirectoryName(relativePath);
string newRelPath = Path.Combine(strSavePath, label);
if (!Path.IsPathRooted(relativePath))
{
strSavePath = Path.Combine(Path.GetDirectoryName(this.ProjectMgr.BaseURI.Uri.LocalPath), strSavePath);
}
string newName = Path.Combine(strSavePath, label);
if (NativeMethods.IsSamePath(newName, this.Url))
{
// If this is really a no-op, then nothing to do
if (String.Compare(newName, this.Url, StringComparison.Ordinal) == 0)
return VSConstants.S_FALSE;
}
else
{
// If the renamed file already exists then quit (unless it is the result of the parent having done the move).
if (IsFileOnDisk(newName)
&& (IsFileOnDisk(this.Url)
|| String.Compare(Path.GetFileName(newName), Path.GetFileName(this.Url), StringComparison.Ordinal) != 0))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileCannotBeRenamedToAnExistingFile, CultureInfo.CurrentUICulture), label));
}
else if (newName.Length > NativeMethods.MAX_PATH)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.PathTooLong, CultureInfo.CurrentUICulture), label));
}
}
string oldName = this.Url;
// must update the caption prior to calling RenameDocument, since it may
// cause queries of that property (such as from open editors).
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
RenameDocument(oldName, newName);
// Return S_FALSE if the hierarchy item id has changed. This forces VS to flush the stale
// hierarchy item id.
if (returnValue == (int)VSConstants.S_OK || returnValue == (int)VSConstants.S_FALSE || returnValue == VSConstants.OLE_E_PROMPTSAVECANCELLED)
{
return (oldId == this.ID) ? VSConstants.S_OK : (int)VSConstants.S_FALSE;
}
return returnValue;
}
/// <summary>
/// Returns a specific Document manager to handle files
/// </summary>
/// <returns>Document manager object</returns>
internal override DocumentManager GetDocumentManager()
{
return new FileDocumentManager(this);
}
/// <summary>
/// Called by the drag&drop implementation to ask the node
/// which is being dragged/droped over which nodes should
/// process the operation.
/// This allows for dragging to a node that cannot contain
/// items to let its parent accept the drop, while a reference
/// node delegate to the project and a folder/project node to itself.
/// </summary>
/// <returns></returns>
public override HierarchyNode GetDragTargetHandlerNode()
{
Debug.Assert(this.ProjectMgr != null, " The project manager is null for the filenode");
HierarchyNode handlerNode = this;
while (handlerNode != null && !(handlerNode is ProjectNode || handlerNode is FolderNode))
handlerNode = handlerNode.Parent;
if (handlerNode == null)
handlerNode = this.ProjectMgr;
return handlerNode;
}
public override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
// Exec on special filenode commands
if (cmdGroup == VsMenus.guidStandardCommandSet97)
{
IVsWindowFrame windowFrame = null;
switch ((VsCommands)cmd)
{
case VsCommands.ViewCode:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Code, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.ViewForm:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Designer, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.Open:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, WindowFrameShowAction.Show);
case VsCommands.OpenWith:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, true, VSConstants.LOGVIEWID_UserChooseView, out windowFrame, WindowFrameShowAction.Show);
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result)
{
if (cmdGroup == VsMenus.guidStandardCommandSet97)
{
switch ((VsCommands)cmd)
{
case VsCommands.Copy:
case VsCommands.Paste:
case VsCommands.Cut:
case VsCommands.Rename:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.ViewCode:
case VsCommands.Open:
case VsCommands.OpenWith:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else if (cmdGroup == VsMenus.guidStandardCommandSet2K)
{
if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT)
{
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else
{
return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP;
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
public override void DoDefaultAction()
{
CCITracing.TraceCall();
FileDocumentManager manager = this.GetDocumentManager() as FileDocumentManager;
Debug.Assert(manager != null, "Could not get the FileDocumentManager");
manager.Open(false, false, WindowFrameShowAction.Show);
}
/// <summary>
/// Performs a SaveAs operation of an open document. Called from SaveItem after the running document table has been updated with the new doc data.
/// </summary>
/// <param name="docData">A pointer to the document in the rdt</param>
/// <param name="newFilePath">The new file path to the document</param>
/// <returns></returns>
public override int AfterSaveItemAs(IntPtr docData, string newFilePath)
{
if (String.IsNullOrEmpty(newFilePath))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newFilePath");
}
int returnCode = VSConstants.S_OK;
newFilePath = newFilePath.Trim();
//Identify if Path or FileName are the same for old and new file
string newDirectoryName = Path.GetDirectoryName(newFilePath);
Uri newDirectoryUri = new Uri(newDirectoryName);
string newCanonicalDirectoryName = newDirectoryUri.LocalPath;
newCanonicalDirectoryName = newCanonicalDirectoryName.TrimEnd(Path.DirectorySeparatorChar);
string oldCanonicalDirectoryName = new Uri(Path.GetDirectoryName(this.GetMkDocument())).LocalPath;
oldCanonicalDirectoryName = oldCanonicalDirectoryName.TrimEnd(Path.DirectorySeparatorChar);
string errorMessage = String.Empty;
bool isSamePath = NativeMethods.IsSamePath(newCanonicalDirectoryName, oldCanonicalDirectoryName);
bool isSameFile = NativeMethods.IsSamePath(newFilePath, this.Url);
// Currently we do not support if the new directory is located outside the project cone
string projectCannonicalDirecoryName = new Uri(this.ProjectMgr.ProjectFolder).LocalPath;
projectCannonicalDirecoryName = projectCannonicalDirecoryName.TrimEnd(Path.DirectorySeparatorChar);
if (!isSamePath && newCanonicalDirectoryName.IndexOf(projectCannonicalDirecoryName, StringComparison.OrdinalIgnoreCase) == -1)
{
errorMessage = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.LinkedItemsAreNotSupported, CultureInfo.CurrentUICulture), Path.GetFileNameWithoutExtension(newFilePath));
throw new InvalidOperationException(errorMessage);
}
//Get target container
HierarchyNode targetContainer = null;
if (isSamePath)
{
targetContainer = this.Parent;
}
else if (NativeMethods.IsSamePath(newCanonicalDirectoryName, projectCannonicalDirecoryName))
{
//the projectnode is the target container
targetContainer = this.ProjectMgr;
}
else
{
//search for the target container among existing child nodes
targetContainer = this.ProjectMgr.FindChild(newDirectoryName);
if (targetContainer != null && (targetContainer is FileNode))
{
// We already have a file node with this name in the hierarchy.
errorMessage = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileAlreadyExistsAndCannotBeRenamed, CultureInfo.CurrentUICulture), Path.GetFileNameWithoutExtension(newFilePath));
throw new InvalidOperationException(errorMessage);
}
}
if (targetContainer == null)
{
// Add a chain of subdirectories to the project.
string relativeUri = PackageUtilities.GetPathDistance(this.ProjectMgr.BaseURI.Uri, newDirectoryUri);
Debug.Assert(!String.IsNullOrEmpty(relativeUri) && relativeUri != newDirectoryUri.LocalPath, "Could not make pat distance of " + this.ProjectMgr.BaseURI.Uri.LocalPath + " and " + newDirectoryUri);
targetContainer = this.ProjectMgr.CreateFolderNodes(relativeUri);
}
Debug.Assert(targetContainer != null, "We should have found a target node by now");
//Suspend file changes while we rename the document
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
string oldName = Path.Combine(this.ProjectMgr.ProjectFolder, oldrelPath);
SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
try
{
// Rename the node.
DocumentManager.UpdateCaption(this.ProjectMgr.Site, Path.GetFileName(newFilePath), docData);
// Check if the file name was actually changed.
// In same cases (e.g. if the item is a file and the user has changed its encoding) this function
// is called even if there is no real rename.
var oldParent = this.Parent;
if (!isSameFile || (oldParent.ID != targetContainer.ID))
{
// The path of the file is changed or its parent is changed; in both cases we have
// to rename the item.
this.RenameFileNode(oldName, newFilePath, targetContainer.ID);
OnInvalidateItems(oldParent);
// This is what othe project systems do; for the purposes of source control, the old file is removed, and a new file is added
// (althought the old file stays on disk!)
this.ProjectMgr.Tracker.OnItemRemoved(oldName, VSREMOVEFILEFLAGS.VSREMOVEFILEFLAGS_NoFlags);
this.ProjectMgr.Tracker.OnItemAdded(newFilePath, VSADDFILEFLAGS.VSADDFILEFLAGS_NoFlags);
}
}
catch (Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
this.RecoverFromRenameFailure(newFilePath, oldrelPath);
throw;
}
finally
{
sfc.Resume();
}
return returnCode;
}
/// <summary>
/// Determines if this is node a valid node for painting the default file icon.
/// </summary>
/// <returns></returns>
public override bool CanShowDefaultIcon()
{
string moniker = this.GetMkDocument();
if (String.IsNullOrEmpty(moniker) || !FSLib.Shim.FileSystem.SafeExists(moniker))
{
return false;
}
return true;
}
public virtual string FileName
{
get
{
return this.Caption;
}
set
{
this.SetEditLabel(value);
}
}
/// <summary>
/// Determine if this item is represented physical on disk and shows a messagebox in case that the file is not present and a UI is to be presented.
/// </summary>
/// <param name="showMessage">true if user should be presented for UI in case the file is not present</param>
/// <returns>true if file is on disk</returns>
public virtual bool IsFileOnDisk(bool showMessage)
{
bool fileExist = IsFileOnDisk(this.Url);
if (!fileExist && showMessage && !Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
{
string message = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.ItemDoesNotExistInProjectDirectory, CultureInfo.CurrentUICulture), this.Caption);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton);
}
return fileExist;
}
/// <summary>
/// Determine if the file represented by "path" exist in storage.
/// Override this method if your files are not persisted on disk.
/// </summary>
/// <param name="path">Url representing the file</param>
/// <returns>True if the file exist</returns>
public virtual bool IsFileOnDisk(string path)
{
return FSLib.Shim.FileSystem.SafeExists(path);
}
/// <summary>
/// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy.
/// </summary>
/// <param name="oldFileName">The old file name.</param>
/// <param name="newFileName">The new file name</param>
/// <param name="newParentId">The new parent id of the item.</param>
/// <returns>The newly added FileNode.</returns>
/// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks>
public virtual FileNode RenameFileNode(string oldFileName, string newFileName, uint newParentId)
{
if (string.Compare(oldFileName, newFileName, StringComparison.Ordinal) == 0)
{
// We do not want to rename the same file
return null;
}
string[] file = new string[1];
file[0] = newFileName;
VSADDRESULT[] result = new VSADDRESULT[1];
Guid emptyGuid = Guid.Empty;
FileNode childAdded = null;
string originalInclude = this.ItemNode.Item.UnevaluatedInclude;
return Transactional.Try(
// Action
() =>
{
// It's unfortunate that MPF implements rename in terms of AddItemWithSpecific. Since this
// is the case, we have to pass false to prevent AddITemWithSpecific to fire Add events on
// the IVsTrackProjectDocuments2 tracker. Otherwise, clients listening to this event
// (SCCI, for example) will be really confused.
using (this.ProjectMgr.ExtensibilityEventsHelper.SuspendEvents())
{
var currentId = this.ID;
// actual deletion is delayed until all checks are passed
Func<uint> getIdOfExistingItem =
() =>
{
this.OnItemDeleted();
this.Parent.RemoveChild(this);
return currentId;
};
// raises OnItemAdded inside
ErrorHandler.ThrowOnFailure(this.ProjectMgr.AddItemWithSpecific(newParentId, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, null, 0, file, IntPtr.Zero, 0, ref emptyGuid, null, ref emptyGuid, result, false, getIdOfExistingItem));
childAdded = this.ProjectMgr.FindChild(newFileName) as FileNode;
Debug.Assert(childAdded != null, "Could not find the renamed item in the hierarchy");
}
},
// Compensation
() =>
{
// it failed, but 'this' is dead and 'childAdded' is here to stay, so fix the latter back
using (this.ProjectMgr.ExtensibilityEventsHelper.SuspendEvents())
{
childAdded.ItemNode.Rename(originalInclude);
childAdded.ItemNode.RefreshProperties();
}
},
// Continuation
() =>
{
// Since this node has been removed all of its state is zombied at this point
// Do not call virtual methods after this point since the object is in a deleted state.
// Remove the item created by the add item. We need to do this otherwise we will have two items.
// Please be aware that we have not removed the ItemNode associated to the removed file node from the hierrachy.
// What we want to achieve here is to reuse the existing build item.
// We want to link to the newly created node to the existing item node and addd the new include.
//temporarily keep properties from new itemnode since we are going to overwrite it
string newInclude = childAdded.ItemNode.Item.UnevaluatedInclude;
string dependentOf = childAdded.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
childAdded.ItemNode.RemoveFromProjectFile();
// Assign existing msbuild item to the new childnode
childAdded.ItemNode = this.ItemNode;
childAdded.ItemNode.Item.ItemType = this.ItemNode.ItemName;
childAdded.ItemNode.Item.Xml.Include = newInclude;
if (!string.IsNullOrEmpty(dependentOf))
childAdded.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, dependentOf);
childAdded.ItemNode.RefreshProperties();
// Extensibilty events has rename
this.ProjectMgr.ExtensibilityEventsHelper.FireItemRenamed(childAdded, Path.GetFileName(originalInclude));
//Update the new document in the RDT.
try
{
DocumentManager.RenameDocument(this.ProjectMgr.Site, oldFileName, newFileName, childAdded.ID);
// The current automation node is renamed, but the hierarchy ID is now pointing to the old item, which
// is invalid. Update it.
this.ID = childAdded.ID;
//Update FirstChild
childAdded.FirstChild = this.FirstChild;
//Update ChildNodes
SetNewParentOnChildNodes(childAdded);
RenameChildNodes(childAdded);
return childAdded;
}
finally
{
//Select the new node in the hierarchy
IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);
uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, childAdded.ID, EXPANDFLAGS.EXPF_SelectItem);
}
});
}
/// <summary>
/// Rename all childnodes
/// </summary>
/// <param name="parentNode">The newly added Parent node.</param>
public virtual void RenameChildNodes(FileNode parentNode)
{
foreach (HierarchyNode child in GetChildNodes())
{
FileNode childNode = child as FileNode;
if (null == childNode)
{
continue;
}
string newfilename;
if (childNode.HasParentNodeNameRelation)
{
string relationalName = childNode.Parent.GetRelationalName();
string extension = childNode.GetRelationNameExtension();
newfilename = relationalName + extension;
newfilename = Path.Combine(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), newfilename);
}
else
{
newfilename = Path.Combine(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), childNode.Caption);
}
childNode.RenameDocument(childNode.GetMkDocument(), newfilename);
//We must update the DependsUpon property since the rename operation will not do it if the childNode is not renamed
//which happens if the is no name relation between the parent and the child
string dependentOf = childNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
if (!string.IsNullOrEmpty(dependentOf))
{
childNode.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, childNode.Parent.ItemNode.GetMetadata(ProjectFileConstants.Include));
}
}
}
/// <summary>
/// Tries recovering from a rename failure.
/// </summary>
/// <param name="fileThatFailed"> The file that failed to be renamed.</param>
/// <param name="originalFileName">The original filenamee</param>
public virtual void RecoverFromRenameFailure(string fileThatFailed, string originalFileName)
{
// TODO does this do anything useful? did it ever change in the first place?
if (this.ItemNode != null && !String.IsNullOrEmpty(originalFileName))
{
this.ItemNode.Rename(originalFileName);
this.ItemNode.RefreshProperties();
}
}
public override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation)
{
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage)
{
return this.ProjectMgr.CanProjectDeleteItems;
}
return false;
}
/// <summary>
/// This should be overriden for node that are not saved on disk
/// </summary>
/// <param name="oldName">Previous name in storage</param>
/// <param name="newName">New name in storage</param>
public virtual void RenameInStorage(string oldName, string newName)
{
File.Move(oldName, newName);
}
/// <summary>
/// This method should be overridden to provide the list of special files and associated flags for source control.
/// </summary>
/// <param name="sccFile">One of the file associated to the node.</param>
/// <param name="files">The list of files to be placed under source control.</param>
/// <param name="flags">The flags that are associated to the files.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "scc")]
public override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags)
{
if (this.ExcludeNodeFromScc)
{
return;
}
if (files == null)
{
throw new ArgumentNullException("files");
}
if (flags == null)
{
throw new ArgumentNullException("flags");
}
foreach (HierarchyNode node in this.GetChildNodes())
{
files.Add(node.GetMkDocument());
}
}
/// <summary>
/// Get's called to rename the eventually running document this hierarchyitem points to
/// </summary>
/// returns FALSE if the doc can not be renamed
public bool RenameDocument(string oldName, string newName)
{
IVsRunningDocumentTable pRDT = this.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (pRDT == null) return false;
IntPtr docData = IntPtr.Zero;
IVsHierarchy pIVsHierarchy;
uint itemId;
uint uiVsDocCookie;
SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
try
{
VSRENAMEFILEFLAGS renameflag = VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags;
ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie));
if (pIVsHierarchy != null && !Utilities.IsSameComObject(pIVsHierarchy, this.ProjectMgr))
{
// Don't rename it if it wasn't opened by us.
return false;
}
// ask other potentially running packages
if (!this.ProjectMgr.Tracker.CanRenameItem(oldName, newName, renameflag))
{
return false;
}
// Allow the user to "fix" the project by renaming the item in the hierarchy
// to the real name of the file on disk.
bool shouldRenameInStorage = IsFileOnDisk(oldName) || !IsFileOnDisk(newName);
Transactional.Try(
// Action
() => { if (shouldRenameInStorage) RenameInStorage(oldName, newName); },
// Compensation
() => { if (shouldRenameInStorage) RenameInStorage(newName, oldName); },
// Continuation
() =>
{
string newFileName = Path.GetFileName(newName);
string oldCaption = this.Caption;
Transactional.Try(
// Action
() => DocumentManager.UpdateCaption(this.ProjectMgr.Site, newFileName, docData),
// Compensation
() => DocumentManager.UpdateCaption(this.ProjectMgr.Site, oldCaption, docData),
// Continuation
() =>
{
bool caseOnlyChange = NativeMethods.IsSamePath(oldName, newName);
if (!caseOnlyChange)
{
// Check out the project file if necessary.
if (!this.ProjectMgr.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
this.RenameFileNode(oldName, newName);
}
else
{
this.RenameCaseOnlyChange(newFileName);
}
bool extensionWasChanged = (0 != String.Compare(Path.GetExtension(oldName), Path.GetExtension(newName), StringComparison.OrdinalIgnoreCase));
if (extensionWasChanged)
{
// Update the BuildAction
this.ItemNode.ItemName = this.ProjectMgr.DefaultBuildAction(newName);
}
this.ProjectMgr.Tracker.OnItemRenamed(oldName, newName, renameflag);
});
});
}
finally
{
if (docData != IntPtr.Zero)
{
Marshal.Release(docData);
}
sfc.Resume(); // can throw, e.g. when RenameFileNode failed, but file was renamed on disk and now editor cannot find file
}
return true;
}
private FileNode RenameFileNode(string oldFileName, string newFileName)
{
return this.RenameFileNode(oldFileName, newFileName, this.Parent.ID);
}
/// <summary>
/// Renames the file node for a case only change.
/// </summary>
/// <param name="newFileName">The new file name.</param>
private void RenameCaseOnlyChange(string newFileName)
{
//Update the include for this item.
string include = this.ItemNode.Item.UnevaluatedInclude;
if (String.Compare(include, newFileName, StringComparison.OrdinalIgnoreCase) == 0)
{
this.ItemNode.Item.Xml.Include = newFileName;
}
else
{
string includeDir = Path.GetDirectoryName(include);
this.ItemNode.Item.Xml.Include = Path.Combine(includeDir, newFileName);
}
this.ItemNode.RefreshProperties();
this.ReDraw(UIHierarchyElement.Caption);
this.RenameChildNodes(this);
// Refresh the property browser.
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Debug.Assert(shell != null, "Could not get the ui shell from the project");
if (shell == null)
{
throw new InvalidOperationException();
}
shell.RefreshPropertyBrowser(0);
//Select the new node in the hierarchy
IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);
uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, this.ID, EXPANDFLAGS.EXPF_SelectItem);
}
/// <summary>
/// Update the ChildNodes after the parent node has been renamed
/// </summary>
/// <param name="newFileNode">The new FileNode created as part of the rename of this node</param>
private void SetNewParentOnChildNodes(FileNode newFileNode)
{
foreach (HierarchyNode childNode in GetChildNodes())
{
childNode.Parent = newFileNode;
}
}
private List<HierarchyNode> GetChildNodes()
{
List<HierarchyNode> childNodes = new List<HierarchyNode>();
HierarchyNode childNode = this.FirstChild;
while (childNode != null)
{
childNodes.Add(childNode);
childNode = childNode.NextSibling;
}
return childNodes;
}
public override __VSPROVISIONALVIEWINGSTATUS ProvisionalViewingStatus =>
IsFileOnDisk(false)
? __VSPROVISIONALVIEWINGSTATUS.PVS_Enabled
: __VSPROVISIONALVIEWINGSTATUS.PVS_Disabled;
}
}
| |
/*
* 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.Tests.Client
{
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Client.Cache;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Impl.Common;
using NUnit.Framework;
/// <summary>
/// Tests client connection: port ranges, version checks, etc.
/// </summary>
public class ClientConnectionTest
{
/** Temp dir for WAL. */
private readonly string _tempDir = TestUtils.GetTempDirectoryName();
/// <summary>
/// Sets up the test.
/// </summary>
[SetUp]
public void SetUp()
{
TestUtils.ClearWorkDir();
}
/// <summary>
/// Test tear down.
/// </summary>
[TearDown]
public void TearDown()
{
Ignition.StopAll(true);
if (Directory.Exists(_tempDir))
{
Directory.Delete(_tempDir, true);
}
TestUtils.ClearWorkDir();
}
/// <summary>
/// Tests that missing server yields connection refused error.
/// </summary>
[Test]
public void TestNoServerConnectionRefused()
{
var ex = Assert.Throws<AggregateException>(() => StartClient());
var socketEx = ex.InnerExceptions.OfType<SocketException>().First();
Assert.AreEqual(SocketError.ConnectionRefused, socketEx.SocketErrorCode);
}
/// <summary>
/// Tests that empty username or password are not allowed.
/// </summary>
[Test]
public void TestAuthenticationEmptyCredentials()
{
using (Ignition.Start(SecureServerConfig()))
{
var cliCfg = GetSecureClientConfig();
cliCfg.Password = null;
var ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); });
Assert.IsTrue(ex.Message.StartsWith("IgniteClientConfiguration.Password cannot be null"));
cliCfg.Password = "";
ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); });
Assert.IsTrue(ex.Message.StartsWith("IgniteClientConfiguration.Password cannot be empty"));
cliCfg.Password = "ignite";
cliCfg.UserName = null;
ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); });
Assert.IsTrue(ex.Message.StartsWith("IgniteClientConfiguration.UserName cannot be null"));
cliCfg.UserName = "";
ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); });
Assert.IsTrue(ex.Message.StartsWith("IgniteClientConfiguration.Username cannot be empty"));
}
}
/// <summary>
/// Test invalid username or password.
/// </summary>
[Test]
public void TestAuthenticationInvalidCredentials()
{
using (Ignition.Start(SecureServerConfig()))
{
var cliCfg = GetSecureClientConfig();
cliCfg.UserName = "invalid";
var ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); });
Assert.True(ex.StatusCode == ClientStatusCode.AuthenticationFailed);
cliCfg.UserName = "ignite";
cliCfg.Password = "invalid";
ex = Assert.Throws<IgniteClientException>(() => { Ignition.StartClient(cliCfg); });
Assert.True(ex.StatusCode == ClientStatusCode.AuthenticationFailed);
}
}
/// <summary>
/// Test authentication.
/// </summary>
[Test]
public void TestAuthentication()
{
CreateNewUserAndAuthenticate("my_User", "my_Password");
}
/// <summary>
/// Test authentication.
/// </summary>
[Test]
public void TestAuthenticationLongToken()
{
string user = new string('G', 59);
string pass = new string('q', 16 * 1024);
CreateNewUserAndAuthenticate(user, pass);
}
/// <summary>
/// Tests that multiple clients can connect to one server.
/// </summary>
[Test]
public void TestMultipleClients()
{
using (Ignition.Start(TestUtils.GetTestConfiguration()))
{
var client1 = StartClient();
var client2 = StartClient();
var client3 = StartClient();
client1.Dispose();
client2.Dispose();
client3.Dispose();
}
}
/// <summary>
/// Tests custom connector and client configuration.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestCustomConfig()
{
var servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
ClientConnectorConfiguration = new ClientConnectorConfiguration
{
Host = "localhost",
Port = 2000,
PortRange = 1,
SocketSendBufferSize = 100,
SocketReceiveBufferSize = 50
}
};
var clientCfg = new IgniteClientConfiguration
{
Endpoints = new[] {"localhost:2000"}
};
using (Ignition.Start(servCfg))
using (var client = Ignition.StartClient(clientCfg))
{
Assert.AreNotEqual(clientCfg, client.GetConfiguration());
Assert.AreNotEqual(client.GetConfiguration(), client.GetConfiguration());
Assert.AreEqual(clientCfg.ToXml(), client.GetConfiguration().ToXml());
}
}
/// <summary>
/// Tests client config with EndPoints property.
/// </summary>
[Test]
public void TestEndPoints()
{
using (var ignite = Ignition.Start(TestUtils.GetTestConfiguration()))
{
ignite.CreateCache<int, int>("foo");
const int port = IgniteClientConfiguration.DefaultPort;
// DnsEndPoint.
var cfg = new IgniteClientConfiguration
{
Endpoints = new[] { "localhost" }
};
using (var client = Ignition.StartClient(cfg))
{
Assert.AreEqual("foo", client.GetCacheNames().Single());
}
// IPEndPoint.
cfg = new IgniteClientConfiguration
{
Endpoints = new[] { "127.0.0.1:" + port }
};
using (var client = Ignition.StartClient(cfg))
{
Assert.AreEqual("foo", client.GetCacheNames().Single());
}
}
}
/// <summary>
/// Tests that default configuration throws.
/// </summary>
[Test]
public void TestDefaultConfigThrows()
{
Assert.Throws<IgniteClientException>(() => Ignition.StartClient(new IgniteClientConfiguration()));
}
/// <summary>
/// Tests the incorrect protocol version error.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestIncorrectProtocolVersionError()
{
using (Ignition.Start(TestUtils.GetTestConfiguration()))
{
// ReSharper disable once ObjectCreationAsStatement
var ex = Assert.Throws<IgniteClientException>(() =>
new ClientSocket(GetClientConfiguration(),
new DnsEndPoint(
"localhost",
ClientConnectorConfiguration.DefaultPort,
AddressFamily.InterNetwork),
null,
new ClientProtocolVersion(-1, -1, -1)));
Assert.AreEqual(ClientStatusCode.Fail, ex.StatusCode);
Assert.IsTrue(Regex.IsMatch(ex.Message, "Client handshake failed: 'Unsupported version.'. " +
"Client version: -1.-1.-1. Server version: [0-9]+.[0-9]+.[0-9]+"));
}
}
/// <summary>
/// Tests that connector can be disabled.
/// </summary>
[Test]
public void TestDisabledConnector()
{
var servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
ClientConnectorConfigurationEnabled = false
};
var clientCfg = new IgniteClientConfiguration
{
Endpoints = new[] {"localhost"}
};
using (Ignition.Start(servCfg))
{
var ex = Assert.Throws<AggregateException>(() => Ignition.StartClient(clientCfg));
Assert.AreEqual("Failed to establish Ignite thin client connection, " +
"examine inner exceptions for details.", ex.Message.Substring(0, 88));
}
// Disable only thin client.
servCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
ClientConnectorConfiguration = new ClientConnectorConfiguration
{
ThinClientEnabled = false
}
};
using (Ignition.Start(servCfg))
{
var ex = Assert.Throws<IgniteClientException>(() => Ignition.StartClient(clientCfg));
Assert.AreEqual("Client handshake failed: 'Thin client connection is not allowed, " +
"see ClientConnectorConfiguration.thinClientEnabled.'.",
ex.Message.Substring(0, 118));
}
}
/// <summary>
/// Tests that we get a proper exception when server disconnects (node shutdown, network issues, etc).
/// </summary>
[Test]
public void TestServerConnectionAborted()
{
var evt = new ManualResetEventSlim();
var ignite = Ignition.Start(TestUtils.GetTestConfiguration());
var putGetTask = TaskRunner.Run(() =>
{
using (var client = StartClient())
{
var cache = client.GetOrCreateCache<int, int>("foo");
evt.Set();
for (var i = 0; i < 100000; i++)
{
cache[i] = i;
Assert.AreEqual(i, cache.GetAsync(i).Result);
}
}
});
evt.Wait();
ignite.Dispose();
var ex = Assert.Throws<AggregateException>(() => putGetTask.Wait());
var baseEx = ex.GetBaseException();
var socketEx = baseEx as SocketException;
if (socketEx != null)
{
Assert.AreEqual(SocketError.ConnectionAborted, socketEx.SocketErrorCode);
}
else
{
Assert.Fail("Unexpected exception: " + ex);
}
}
/// <summary>
/// Tests the operation timeout.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestOperationTimeout()
{
var data = Enumerable.Range(1, 500000).ToDictionary(x => x, x => x.ToString());
Ignition.Start(TestUtils.GetTestConfiguration());
var cfg = GetClientConfiguration();
cfg.SocketTimeout = TimeSpan.FromMilliseconds(500);
var client = Ignition.StartClient(cfg);
var cache = client.CreateCache<int, string>("s");
Assert.AreEqual(cfg.SocketTimeout, client.GetConfiguration().SocketTimeout);
// Async.
var task = cache.PutAllAsync(data);
Assert.IsFalse(task.IsCompleted);
var ex = Assert.Catch(() => task.Wait());
Assert.AreEqual(SocketError.TimedOut, GetSocketException(ex).SocketErrorCode);
// Sync (reconnect for clean state).
Ignition.StopAll(true);
Ignition.Start(TestUtils.GetTestConfiguration());
client = Ignition.StartClient(cfg);
cache = client.CreateCache<int, string>("s");
ex = Assert.Catch(() => cache.PutAll(data));
Assert.AreEqual(SocketError.TimedOut, GetSocketException(ex).SocketErrorCode);
}
/// <summary>
/// Tests the client dispose while operations are in progress.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestClientDisposeWhileOperationsAreInProgress()
{
Ignition.Start(TestUtils.GetTestConfiguration());
const int count = 100000;
var ops = new Task[count];
using (var client = StartClient())
{
var cache = client.GetOrCreateCache<int, int>("foo");
Parallel.For(0, count, new ParallelOptions {MaxDegreeOfParallelism = 16},
i =>
{
ops[i] = cache.PutAsync(i, i);
});
}
var completed = ops.Count(x => x.Status == TaskStatus.RanToCompletion);
Assert.Greater(completed, 0, "Some tasks should have completed.");
var failed = ops.Where(x => x.Status == TaskStatus.Faulted).ToArray();
Assert.IsTrue(failed.Any(), "Some tasks should have failed.");
foreach (var task in failed)
{
var ex = task.Exception;
Assert.IsNotNull(ex);
var baseEx = ex.GetBaseException();
Assert.IsNotNull((object) (baseEx as SocketException) ?? baseEx as ObjectDisposedException,
ex.ToString());
}
}
/// <summary>
/// Tests the <see cref="ClientConnectorConfiguration.IdleTimeout"/> property.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestIdleTimeout()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
ClientConnectorConfiguration = new ClientConnectorConfiguration
{
IdleTimeout = TimeSpan.FromMilliseconds(100)
}
};
var ignite = Ignition.Start(cfg);
Assert.AreEqual(100, ignite.GetConfiguration().ClientConnectorConfiguration.IdleTimeout.TotalMilliseconds);
using (var client = StartClient())
{
var cache = client.GetOrCreateCache<int, int>("foo");
cache[1] = 1;
Assert.AreEqual(1, cache[1]);
Thread.Sleep(90);
Assert.AreEqual(1, cache[1]);
// Idle check frequency is 2 seconds.
Thread.Sleep(4000);
var ex = Assert.Catch(() => cache.Get(1));
Assert.AreEqual(SocketError.ConnectionAborted, GetSocketException(ex).SocketErrorCode);
}
}
/// <summary>
/// Tests the protocol mismatch behavior: attempt to connect to an HTTP endpoint.
/// </summary>
[Test]
public void TestProtocolMismatch()
{
using (Ignition.Start(TestUtils.GetTestConfiguration()))
{
// Connect to Ignite REST endpoint.
var cfg = new IgniteClientConfiguration("127.0.0.1:11211");
var ex = GetSocketException(Assert.Catch(() => Ignition.StartClient(cfg)));
Assert.AreEqual(SocketError.ConnectionAborted, ex.SocketErrorCode);
}
}
/// <summary>
/// Tests reconnect logic with single server.
/// </summary>
[Test]
public void TestReconnect()
{
// Connect client and check.
Ignition.Start(TestUtils.GetTestConfiguration());
var client = Ignition.StartClient(new IgniteClientConfiguration("127.0.0.1"));
Assert.AreEqual(0, client.GetCacheNames().Count);
var ep = client.RemoteEndPoint as IPEndPoint;
Assert.IsNotNull(ep);
Assert.AreEqual(IgniteClientConfiguration.DefaultPort, ep.Port);
Assert.AreEqual("127.0.0.1", ep.Address.ToString());
ep = client.LocalEndPoint as IPEndPoint;
Assert.IsNotNull(ep);
Assert.AreNotEqual(IgniteClientConfiguration.DefaultPort, ep.Port);
Assert.AreEqual("127.0.0.1", ep.Address.ToString());
// Stop server.
Ignition.StopAll(true);
// First request fails, error is detected.
var ex = Assert.Catch(() => client.GetCacheNames());
Assert.IsNotNull(GetSocketException(ex));
// Second request causes reconnect attempt which fails (server is stopped).
Assert.Catch(() => client.GetCacheNames());
// Start server, next operation succeeds.
Ignition.Start(TestUtils.GetTestConfiguration());
Assert.AreEqual(0, client.GetCacheNames().Count);
}
/// <summary>
/// Tests disabled reconnect behavior.
/// </summary>
[Test]
public void TestReconnectDisabled()
{
// Connect client and check.
Ignition.Start(TestUtils.GetTestConfiguration());
using (var client = Ignition.StartClient(new IgniteClientConfiguration("127.0.0.1")
{
ReconnectDisabled = true
}))
{
Assert.AreEqual(0, client.GetCacheNames().Count);
// Stop server.
Ignition.StopAll(true);
// Request fails, error is detected.
var ex = Assert.Catch(() => client.GetCacheNames());
Assert.IsNotNull(GetSocketException(ex));
// Restart server, client does not reconnect.
Ignition.Start(TestUtils.GetTestConfiguration());
ex = Assert.Catch(() => client.GetCacheNames());
Assert.IsNotNull(GetSocketException(ex));
}
}
/// <summary>
/// Tests reconnect logic with multiple servers.
/// </summary>
[Test]
public void TestFailover()
{
// Start 3 nodes.
Ignition.Start(TestUtils.GetTestConfiguration(name: "0"));
Ignition.Start(TestUtils.GetTestConfiguration(name: "1"));
Ignition.Start(TestUtils.GetTestConfiguration(name: "2"));
// Connect client.
var port = IgniteClientConfiguration.DefaultPort;
var cfg = new IgniteClientConfiguration
{
Endpoints = new[]
{
"localhost",
string.Format("127.0.0.1:{0}..{1}", port + 1, port + 2)
}
};
using (var client = Ignition.StartClient(cfg))
{
Assert.AreEqual(0, client.GetCacheNames().Count);
// Stop target node.
var nodeId = ((IPEndPoint) client.RemoteEndPoint).Port - port;
Ignition.Stop(nodeId.ToString(), true);
// Check failure.
Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames())));
// Check reconnect.
Assert.AreEqual(0, client.GetCacheNames().Count);
// Stop target node.
nodeId = ((IPEndPoint) client.RemoteEndPoint).Port - port;
Ignition.Stop(nodeId.ToString(), true);
// Check failure.
Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames())));
// Check reconnect.
Assert.AreEqual(0, client.GetCacheNames().Count);
// Stop all nodes.
Ignition.StopAll(true);
Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames())));
Assert.IsNotNull(GetSocketException(Assert.Catch(() => client.GetCacheNames())));
}
}
/// <summary>
/// Starts the client.
/// </summary>
private static IIgniteClient StartClient()
{
return Ignition.StartClient(GetClientConfiguration());
}
/// <summary>
/// Gets the client configuration.
/// </summary>
private static IgniteClientConfiguration GetClientConfiguration()
{
return new IgniteClientConfiguration(IPAddress.Loopback.ToString());
}
/// <summary>
/// Finds SocketException in the hierarchy.
/// </summary>
private static SocketException GetSocketException(Exception ex)
{
Assert.IsNotNull(ex);
var origEx = ex;
while (ex != null)
{
var socketEx = ex as SocketException;
if (socketEx != null)
{
return socketEx;
}
ex = ex.InnerException;
}
throw new Exception("SocketException not found.", origEx);
}
/// <summary>
/// Create server configuration with enabled authentication.
/// </summary>
/// <returns>Server configuration.</returns>
private IgniteConfiguration SecureServerConfig()
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
AuthenticationEnabled = true,
DataStorageConfiguration = new DataStorageConfiguration
{
StoragePath = Path.Combine(_tempDir, "Store"),
WalPath = Path.Combine(_tempDir, "WalStore"),
WalArchivePath = Path.Combine(_tempDir, "WalArchive"),
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
Name = "default",
PersistenceEnabled = true
}
}
};
}
/// <summary>
/// Create client configuration with enabled authentication.
/// </summary>
/// <returns>Client configuration.</returns>
private static IgniteClientConfiguration GetSecureClientConfig()
{
return new IgniteClientConfiguration("localhost")
{
UserName = "ignite",
Password = "ignite"
};
}
/// <summary>
/// Start new node, create new user with given credentials and try to authenticate.
/// </summary>
/// <param name="user">Username</param>
/// <param name="pass">Password</param>
private void CreateNewUserAndAuthenticate(string user, string pass)
{
using (var srv = Ignition.Start(SecureServerConfig()))
{
srv.GetCluster().SetActive(true);
using (var cli = Ignition.StartClient(GetSecureClientConfig()))
{
CacheClientConfiguration ccfg = new CacheClientConfiguration
{
Name = "TestCache",
QueryEntities = new[]
{
new QueryEntity
{
KeyType = typeof(string),
ValueType = typeof(string),
},
},
};
ICacheClient<string, string> cache = cli.GetOrCreateCache<string, string>(ccfg);
cache.Put("key1", "val1");
cache.Query(new SqlFieldsQuery("CREATE USER \"" + user + "\" WITH PASSWORD '" + pass + "'")).GetAll();
}
var cliCfg = GetSecureClientConfig();
cliCfg.UserName = user;
cliCfg.Password = pass;
using (var cli = Ignition.StartClient(cliCfg))
{
ICacheClient<string, string> cache = cli.GetCache<string, string>("TestCache");
string val = cache.Get("key1");
Assert.True(val == "val1");
}
}
}
}
}
| |
/*
* Copyright (c) Contributors
* 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.
*/
// to build without references to System.Drawing, comment this out
#define SYSTEM_DRAWING
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
#if SYSTEM_DRAWING
using System.Drawing;
using System.Drawing.Imaging;
#endif
namespace PrimMesher
{
public class SculptMesh
{
public List<Coord> coords;
public List<Face> faces;
public List<ViewerFace> viewerFaces;
public List<Coord> normals;
public List<UVCoord> uvs;
public enum SculptType { sphere = 1, torus = 2, plane = 3, cylinder = 4 };
#if SYSTEM_DRAWING
private Bitmap ScaleImage(Bitmap srcImage, float scale, bool removeAlpha)
{
int sourceWidth = srcImage.Width;
int sourceHeight = srcImage.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
int destWidth = (int)(srcImage.Width * scale);
int destHeight = (int)(srcImage.Height * scale);
Bitmap scaledImage;
if (removeAlpha)
{
if (srcImage.PixelFormat == PixelFormat.Format32bppArgb)
for (int y = 0; y < srcImage.Height; y++)
for (int x = 0; x < srcImage.Width; x++)
{
Color c = srcImage.GetPixel(x, y);
srcImage.SetPixel(x, y, Color.FromArgb(255, c.R, c.G, c.B));
}
scaledImage = new Bitmap(destWidth, destHeight,
PixelFormat.Format24bppRgb);
}
else
scaledImage = new Bitmap(srcImage, destWidth, destHeight);
scaledImage.SetResolution(96.0f, 96.0f);
Graphics grPhoto = Graphics.FromImage(scaledImage);
grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
grPhoto.DrawImage(srcImage,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return scaledImage;
}
public SculptMesh SculptMeshFromFile(string fileName, SculptType sculptType, int lod, bool viewerMode)
{
Bitmap bitmap = (Bitmap)Bitmap.FromFile(fileName);
SculptMesh sculptMesh = new SculptMesh(bitmap, sculptType, lod, viewerMode);
bitmap.Dispose();
return sculptMesh;
}
public SculptMesh(string fileName, int sculptType, int lod, int viewerMode, int mirror, int invert)
{
Bitmap bitmap = (Bitmap)Bitmap.FromFile(fileName);
_SculptMesh(bitmap, (SculptType)sculptType, lod, viewerMode != 0, mirror != 0, invert != 0);
bitmap.Dispose();
}
#endif
/// <summary>
/// ** Experimental ** May disappear from future versions ** not recommeneded for use in applications
/// Construct a sculpt mesh from a 2D array of floats
/// </summary>
/// <param name="zMap"></param>
/// <param name="xBegin"></param>
/// <param name="xEnd"></param>
/// <param name="yBegin"></param>
/// <param name="yEnd"></param>
/// <param name="viewerMode"></param>
public SculptMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float yEnd, bool viewerMode)
{
float xStep, yStep;
float uStep, vStep;
int numYElements = zMap.GetLength(0);
int numXElements = zMap.GetLength(1);
try
{
xStep = (xEnd - xBegin) / (float)(numXElements - 1);
yStep = (yEnd - yBegin) / (float)(numYElements - 1);
uStep = 1.0f / (numXElements - 1);
vStep = 1.0f / (numYElements - 1);
}
catch (DivideByZeroException)
{
return;
}
coords = new List<Coord>();
faces = new List<Face>();
normals = new List<Coord>();
uvs = new List<UVCoord>();
viewerFaces = new List<ViewerFace>();
int p1, p2, p3, p4;
int x, y;
int xStart = 0, yStart = 0;
for (y = yStart; y < numYElements; y++)
{
int rowOffset = y * numXElements;
for (x = xStart; x < numXElements; x++)
{
/*
* p1-----p2
* | \ f2 |
* | \ |
* | f1 \|
* p3-----p4
*/
p4 = rowOffset + x;
p3 = p4 - 1;
p2 = p4 - numXElements;
p1 = p3 - numXElements;
Coord c = new Coord(xBegin + x * xStep, yBegin + y * yStep, zMap[y, x]);
this.coords.Add(c);
if (viewerMode)
{
this.normals.Add(new Coord());
this.uvs.Add(new UVCoord(uStep * x, 1.0f - vStep * y));
}
if (y > 0 && x > 0)
{
Face f1, f2;
if (viewerMode)
{
f1 = new Face(p1, p4, p3, p1, p4, p3);
f1.uv1 = p1;
f1.uv2 = p4;
f1.uv3 = p3;
f2 = new Face(p1, p2, p4, p1, p2, p4);
f2.uv1 = p1;
f2.uv2 = p2;
f2.uv3 = p4;
}
else
{
f1 = new Face(p1, p4, p3);
f2 = new Face(p1, p2, p4);
}
this.faces.Add(f1);
this.faces.Add(f2);
}
}
}
if (viewerMode)
calcVertexNormals(SculptType.plane, numXElements, numYElements);
}
#if SYSTEM_DRAWING
public SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode)
{
_SculptMesh(sculptBitmap, sculptType, lod, viewerMode, false, false);
}
public SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, bool invert)
{
_SculptMesh(sculptBitmap, sculptType, lod, viewerMode, mirror, invert);
}
#endif
public SculptMesh(List<List<Coord>> rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert)
{
_SculptMesh(rows, sculptType, viewerMode, mirror, invert);
}
#if SYSTEM_DRAWING
/// <summary>
/// converts a bitmap to a list of lists of coords, while scaling the image.
/// the scaling is done in floating point so as to allow for reduced vertex position
/// quantization as the position will be averaged between pixel values. this routine will
/// likely fail if the bitmap width and height are not powers of 2.
/// </summary>
/// <param name="bitmap"></param>
/// <param name="scale"></param>
/// <param name="mirror"></param>
/// <returns></returns>
private List<List<Coord>> bitmap2Coords(Bitmap bitmap, int scale, bool mirror)
{
int numRows = bitmap.Height / scale;
int numCols = bitmap.Width / scale;
List<List<Coord>> rows = new List<List<Coord>>(numRows);
float pixScale = 1.0f / (scale * scale);
pixScale /= 255;
int imageX, imageY = 0;
int rowNdx, colNdx;
for (rowNdx = 0; rowNdx < numRows; rowNdx++)
{
List<Coord> row = new List<Coord>(numCols);
for (colNdx = 0; colNdx < numCols; colNdx++)
{
imageX = colNdx * scale;
int imageYStart = rowNdx * scale;
int imageYEnd = imageYStart + scale;
int imageXEnd = imageX + scale;
float rSum = 0.0f;
float gSum = 0.0f;
float bSum = 0.0f;
for (; imageX < imageXEnd; imageX++)
{
for (imageY = imageYStart; imageY < imageYEnd; imageY++)
{
Color c = bitmap.GetPixel(imageX, imageY);
if (c.A != 255)
{
bitmap.SetPixel(imageX, imageY, Color.FromArgb(255, c.R, c.G, c.B));
c = bitmap.GetPixel(imageX, imageY);
}
rSum += c.R;
gSum += c.G;
bSum += c.B;
}
}
if (mirror)
row.Add(new Coord(-(rSum * pixScale - 0.5f), gSum * pixScale - 0.5f, bSum * pixScale - 0.5f));
else
row.Add(new Coord(rSum * pixScale - 0.5f, gSum * pixScale - 0.5f, bSum * pixScale - 0.5f));
}
rows.Add(row);
}
return rows;
}
void _SculptMesh(Bitmap sculptBitmap, SculptType sculptType, int lod, bool viewerMode, bool mirror, bool invert)
{
coords = new List<Coord>();
faces = new List<Face>();
normals = new List<Coord>();
uvs = new List<UVCoord>();
sculptType = (SculptType)(((int)sculptType) & 0x07);
if (mirror)
if (sculptType == SculptType.plane)
invert = !invert;
float sculptBitmapLod = (float)Math.Sqrt(sculptBitmap.Width * sculptBitmap.Height);
float sourceScaleFactor = (float)(lod) / sculptBitmapLod;
float fScale = 1.0f / sourceScaleFactor;
int iScale = (int)fScale;
if (iScale < 1) iScale = 1;
if (iScale > 2 && iScale % 2 == 0)
_SculptMesh(bitmap2Coords(ScaleImage(sculptBitmap, 64.0f / sculptBitmapLod, true), 64 / lod, mirror), sculptType, viewerMode, mirror, invert);
else
_SculptMesh(bitmap2Coords(sculptBitmap, iScale, mirror), sculptType, viewerMode, mirror, invert);
}
#endif
void _SculptMesh(List<List<Coord>> rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert)
{
coords = new List<Coord>();
faces = new List<Face>();
normals = new List<Coord>();
uvs = new List<UVCoord>();
sculptType = (SculptType)(((int)sculptType) & 0x07);
if (mirror)
if (sculptType == SculptType.plane)
invert = !invert;
viewerFaces = new List<ViewerFace>();
int width = rows[0].Count;
int p1, p2, p3, p4;
int imageX, imageY;
if (sculptType != SculptType.plane)
{
for (int rowNdx = 0; rowNdx < rows.Count; rowNdx++)
rows[rowNdx].Add(rows[rowNdx][0]);
}
Coord topPole = rows[0][width / 2];
Coord bottomPole = rows[rows.Count - 1][width / 2];
if (sculptType == SculptType.sphere)
{
int count = rows[0].Count;
List<Coord> topPoleRow = new List<Coord>(count);
List<Coord> bottomPoleRow = new List<Coord>(count);
for (int i = 0; i < count; i++)
{
topPoleRow.Add(topPole);
bottomPoleRow.Add(bottomPole);
}
rows.Insert(0, topPoleRow);
rows.Add(bottomPoleRow);
}
else if (sculptType == SculptType.torus)
rows.Add(rows[0]);
int coordsDown = rows.Count;
int coordsAcross = rows[0].Count;
float widthUnit = 1.0f / (coordsAcross - 1);
float heightUnit = 1.0f / (coordsDown - 1);
for (imageY = 0; imageY < coordsDown; imageY++)
{
int rowOffset = imageY * coordsAcross;
for (imageX = 0; imageX < coordsAcross; imageX++)
{
/*
* p1-----p2
* | \ f2 |
* | \ |
* | f1 \|
* p3-----p4
*/
p4 = rowOffset + imageX;
p3 = p4 - 1;
p2 = p4 - coordsAcross;
p1 = p3 - coordsAcross;
this.coords.Add(rows[imageY][imageX]);
if (viewerMode)
{
this.normals.Add(new Coord());
this.uvs.Add(new UVCoord(widthUnit * imageX, heightUnit * imageY));
}
if (imageY > 0 && imageX > 0)
{
Face f1, f2;
if (viewerMode)
{
if (invert)
{
f1 = new Face(p1, p4, p3, p1, p4, p3);
f1.uv1 = p1;
f1.uv2 = p4;
f1.uv3 = p3;
f2 = new Face(p1, p2, p4, p1, p2, p4);
f2.uv1 = p1;
f2.uv2 = p2;
f2.uv3 = p4;
}
else
{
f1 = new Face(p1, p3, p4, p1, p3, p4);
f1.uv1 = p1;
f1.uv2 = p3;
f1.uv3 = p4;
f2 = new Face(p1, p4, p2, p1, p4, p2);
f2.uv1 = p1;
f2.uv2 = p4;
f2.uv3 = p2;
}
}
else
{
if (invert)
{
f1 = new Face(p1, p4, p3);
f2 = new Face(p1, p2, p4);
}
else
{
f1 = new Face(p1, p3, p4);
f2 = new Face(p1, p4, p2);
}
}
this.faces.Add(f1);
this.faces.Add(f2);
}
}
}
if (viewerMode)
calcVertexNormals(sculptType, coordsAcross, coordsDown);
}
/// <summary>
/// Duplicates a SculptMesh object. All object properties are copied by value, including lists.
/// </summary>
/// <returns></returns>
public SculptMesh Copy()
{
return new SculptMesh(this);
}
public SculptMesh(SculptMesh sm)
{
coords = new List<Coord>(sm.coords);
faces = new List<Face>(sm.faces);
viewerFaces = new List<ViewerFace>(sm.viewerFaces);
normals = new List<Coord>(sm.normals);
uvs = new List<UVCoord>(sm.uvs);
}
private void calcVertexNormals(SculptType sculptType, int xSize, int ySize)
{ // compute vertex normals by summing all the surface normals of all the triangles sharing
// each vertex and then normalizing
int numFaces = this.faces.Count;
for (int i = 0; i < numFaces; i++)
{
Face face = this.faces[i];
Coord surfaceNormal = face.SurfaceNormal(this.coords);
this.normals[face.n1] += surfaceNormal;
this.normals[face.n2] += surfaceNormal;
this.normals[face.n3] += surfaceNormal;
}
int numNormals = this.normals.Count;
for (int i = 0; i < numNormals; i++)
this.normals[i] = this.normals[i].Normalize();
if (sculptType != SculptType.plane)
{ // blend the vertex normals at the cylinder seam
for (int y = 0; y < ySize; y++)
{
int rowOffset = y * xSize;
this.normals[rowOffset] = this.normals[rowOffset + xSize - 1] = (this.normals[rowOffset] + this.normals[rowOffset + xSize - 1]).Normalize();
}
}
foreach (Face face in this.faces)
{
ViewerFace vf = new ViewerFace(0);
vf.v1 = this.coords[face.v1];
vf.v2 = this.coords[face.v2];
vf.v3 = this.coords[face.v3];
vf.coordIndex1 = face.v1;
vf.coordIndex2 = face.v2;
vf.coordIndex3 = face.v3;
vf.n1 = this.normals[face.n1];
vf.n2 = this.normals[face.n2];
vf.n3 = this.normals[face.n3];
vf.uv1 = this.uvs[face.uv1];
vf.uv2 = this.uvs[face.uv2];
vf.uv3 = this.uvs[face.uv3];
this.viewerFaces.Add(vf);
}
}
/// <summary>
/// Adds a value to each XYZ vertex coordinate in the mesh
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
public void AddPos(float x, float y, float z)
{
int i;
int numVerts = this.coords.Count;
Coord vert;
for (i = 0; i < numVerts; i++)
{
vert = this.coords[i];
vert.X += x;
vert.Y += y;
vert.Z += z;
this.coords[i] = vert;
}
if (this.viewerFaces != null)
{
int numViewerFaces = this.viewerFaces.Count;
for (i = 0; i < numViewerFaces; i++)
{
ViewerFace v = this.viewerFaces[i];
v.AddPos(x, y, z);
this.viewerFaces[i] = v;
}
}
}
/// <summary>
/// Rotates the mesh
/// </summary>
/// <param name="q"></param>
public void AddRot(Quat q)
{
int i;
int numVerts = this.coords.Count;
for (i = 0; i < numVerts; i++)
this.coords[i] *= q;
int numNormals = this.normals.Count;
for (i = 0; i < numNormals; i++)
this.normals[i] *= q;
if (this.viewerFaces != null)
{
int numViewerFaces = this.viewerFaces.Count;
for (i = 0; i < numViewerFaces; i++)
{
ViewerFace v = this.viewerFaces[i];
v.v1 *= q;
v.v2 *= q;
v.v3 *= q;
v.n1 *= q;
v.n2 *= q;
v.n3 *= q;
this.viewerFaces[i] = v;
}
}
}
public void Scale(float x, float y, float z)
{
int i;
int numVerts = this.coords.Count;
Coord m = new Coord(x, y, z);
for (i = 0; i < numVerts; i++)
this.coords[i] *= m;
if (this.viewerFaces != null)
{
int numViewerFaces = this.viewerFaces.Count;
for (i = 0; i < numViewerFaces; i++)
{
ViewerFace v = this.viewerFaces[i];
v.v1 *= m;
v.v2 *= m;
v.v3 *= m;
this.viewerFaces[i] = v;
}
}
}
public void DumpRaw(String path, String name, String title)
{
if (path == null)
return;
String fileName = name + "_" + title + ".raw";
String completePath = System.IO.Path.Combine(path, fileName);
StreamWriter sw = new StreamWriter(completePath);
for (int i = 0; i < this.faces.Count; i++)
{
string s = this.coords[this.faces[i].v1].ToString();
s += " " + this.coords[this.faces[i].v2].ToString();
s += " " + this.coords[this.faces[i].v3].ToString();
sw.WriteLine(s);
}
sw.Close();
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
namespace Microsoft.Zelig.Test
{
public class StructStructTests : TestBase, ITestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests");
Log.Comment("These tests examine the conversion (casting) of two structs");
Log.Comment("There are two structs S and T");
Log.Comment("The names of the tests describe the tests by listing which two objects will be converted between");
Log.Comment("Followed by which (The source or the destination) will contain a cast definition");
Log.Comment("Followed further by 'i's or 'e's to indicate which of the cast definition and the actual cast are");
Log.Comment("implicit or explicit.");
Log.Comment("");
Log.Comment("For example, S_T_Source_i_e tests the conversion of S to T, with an implicit definition");
Log.Comment("of the cast in the S struct, and an explicit cast in the body of the method.");
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
public override TestResult Run( string[] args )
{
TestResult result = TestResult.Pass;
string testName = "StructStruct_";
int testNumber = 0;
result |= Assert.CheckFailed( StructStruct_S_T_Source_i_i_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( StructStruct_S_T_Source_i_e_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( StructStruct_S_T_Source_e_e_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( StructStruct_S_T_Dest_i_i_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( StructStruct_S_T_Dest_i_e_Test( ), testName, ++testNumber );
result |= Assert.CheckFailed( StructStruct_S_T_Dest_e_e_Test( ), testName, ++testNumber );
return result;
}
//StructStruct Test methods
//The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\StructStruct
//Test Case Calls
[TestMethod]
public TestResult StructStruct_S_T_Source_i_i_Test()
{
if (StructStructTestClass_S_T_Source_i_i.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult StructStruct_S_T_Source_i_e_Test()
{
if (StructStructTestClass_S_T_Source_i_e.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult StructStruct_S_T_Source_e_e_Test()
{
if (StructStructTestClass_S_T_Source_e_e.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult StructStruct_S_T_Dest_i_i_Test()
{
if (StructStructTestClass_S_T_Dest_i_i.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult StructStruct_S_T_Dest_i_e_Test()
{
if (StructStructTestClass_S_T_Dest_i_e.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult StructStruct_S_T_Dest_e_e_Test()
{
if (StructStructTestClass_S_T_Dest_e_e.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
//Compiled Test Cases
struct StructStructTestClass_S_T_Source_i_i_S
{
static public implicit operator StructStructTestClass_S_T_Source_i_i_T(StructStructTestClass_S_T_Source_i_i_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Source_i_i_S to StructStructTestClass_S_T_Source_i_i_T Source implicit");
return new StructStructTestClass_S_T_Source_i_i_T();
}
}
struct StructStructTestClass_S_T_Source_i_i_T
{
}
class StructStructTestClass_S_T_Source_i_i
{
public static void Main_old()
{
StructStructTestClass_S_T_Source_i_i_S s = new StructStructTestClass_S_T_Source_i_i_S();
StructStructTestClass_S_T_Source_i_i_T t;
try
{
t = s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
struct StructStructTestClass_S_T_Source_i_e_S
{
static public implicit operator StructStructTestClass_S_T_Source_i_e_T(StructStructTestClass_S_T_Source_i_e_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Source_i_e_S to StructStructTestClass_S_T_Source_i_e_T Source implicit");
return new StructStructTestClass_S_T_Source_i_e_T();
}
}
struct StructStructTestClass_S_T_Source_i_e_T
{
}
class StructStructTestClass_S_T_Source_i_e
{
public static void Main_old()
{
StructStructTestClass_S_T_Source_i_e_S s = new StructStructTestClass_S_T_Source_i_e_S();
StructStructTestClass_S_T_Source_i_e_T t;
try
{
t = (StructStructTestClass_S_T_Source_i_e_T)s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
struct StructStructTestClass_S_T_Source_e_e_S
{
static public explicit operator StructStructTestClass_S_T_Source_e_e_T(StructStructTestClass_S_T_Source_e_e_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Source_e_e_S to StructStructTestClass_S_T_Source_e_e_T Source explicit");
return new StructStructTestClass_S_T_Source_e_e_T();
}
}
struct StructStructTestClass_S_T_Source_e_e_T
{
}
class StructStructTestClass_S_T_Source_e_e
{
public static void Main_old()
{
StructStructTestClass_S_T_Source_e_e_S s = new StructStructTestClass_S_T_Source_e_e_S();
StructStructTestClass_S_T_Source_e_e_T t;
try
{
t = (StructStructTestClass_S_T_Source_e_e_T)s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
struct StructStructTestClass_S_T_Dest_i_i_S
{
}
struct StructStructTestClass_S_T_Dest_i_i_T
{
static public implicit operator StructStructTestClass_S_T_Dest_i_i_T(StructStructTestClass_S_T_Dest_i_i_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Dest_i_i_S to StructStructTestClass_S_T_Dest_i_i_T Dest implicit");
return new StructStructTestClass_S_T_Dest_i_i_T();
}
}
class StructStructTestClass_S_T_Dest_i_i
{
public static void Main_old()
{
StructStructTestClass_S_T_Dest_i_i_S s = new StructStructTestClass_S_T_Dest_i_i_S();
StructStructTestClass_S_T_Dest_i_i_T t;
try
{
t = s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
struct StructStructTestClass_S_T_Dest_i_e_S
{
}
struct StructStructTestClass_S_T_Dest_i_e_T
{
static public implicit operator StructStructTestClass_S_T_Dest_i_e_T(StructStructTestClass_S_T_Dest_i_e_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Dest_i_e_S to StructStructTestClass_S_T_Dest_i_e_T Dest implicit");
return new StructStructTestClass_S_T_Dest_i_e_T();
}
}
class StructStructTestClass_S_T_Dest_i_e
{
public static void Main_old()
{
StructStructTestClass_S_T_Dest_i_e_S s = new StructStructTestClass_S_T_Dest_i_e_S();
StructStructTestClass_S_T_Dest_i_e_T t;
try
{
t = (StructStructTestClass_S_T_Dest_i_e_T)s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
struct StructStructTestClass_S_T_Dest_e_e_S
{
}
struct StructStructTestClass_S_T_Dest_e_e_T
{
static public explicit operator StructStructTestClass_S_T_Dest_e_e_T(StructStructTestClass_S_T_Dest_e_e_S foo)
{
Log.Comment(" StructStructTestClass_S_T_Dest_e_e_S to StructStructTestClass_S_T_Dest_e_e_T Dest explicit");
return new StructStructTestClass_S_T_Dest_e_e_T();
}
}
class StructStructTestClass_S_T_Dest_e_e
{
public static void Main_old()
{
StructStructTestClass_S_T_Dest_e_e_S s = new StructStructTestClass_S_T_Dest_e_e_S();
StructStructTestClass_S_T_Dest_e_e_T t;
try
{
t = (StructStructTestClass_S_T_Dest_e_e_T)s;
}
catch (System.Exception)
{
Log.Comment("System.Exception Caught");
}
}
public static bool testMethod()
{
Main_old();
return true;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Microsoft.Build.Execution;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Framework;
using System.Collections;
using System;
using System.Diagnostics;
using Microsoft.Build.Construction;
using System.IO;
using System.Xml;
using System.Linq;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Engine.UnitTests;
using Microsoft.Build.Shared;
using Microsoft.Build.UnitTests.BackEnd;
using Microsoft.Build.Utilities;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
using static Microsoft.Build.Engine.UnitTests.TestComparers.ProjectInstanceModelTestComparers;
namespace Microsoft.Build.UnitTests.OM.Instance
{
/// <summary>
/// Tests for ProjectInstance internal members
/// </summary>
public class ProjectInstance_Internal_Tests
{
private readonly ITestOutputHelper _output;
public ProjectInstance_Internal_Tests(ITestOutputHelper output)
{
_output = output;
}
/// <summary>
/// Read task registrations
/// </summary>
[Fact]
public void GetTaskRegistrations()
{
try
{
string projectFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='t0' AssemblyFile='af0'/>
<UsingTask TaskName='t1' AssemblyFile='af1a'/>
<ItemGroup>
<i Include='i0'/>
</ItemGroup>
<Import Project='{0}'/>
</Project>";
string importContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='t1' AssemblyName='an1' Condition=""'$(p)'=='v'""/>
<UsingTask TaskName='t2' AssemblyName='an2' Condition=""'@(i)'=='i0'""/>
<UsingTask TaskName='t3' AssemblyFile='af' Condition='false'/>
<PropertyGroup>
<p>v</p>
</PropertyGroup>
</Project>";
string importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.targets", importContent);
projectFileContent = String.Format(projectFileContent, importPath);
ProjectInstance project = new Project(ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)))).CreateProjectInstance();
Assert.Equal(3, project.TaskRegistry.TaskRegistrations.Count);
Assert.Equal(Path.Combine(Directory.GetCurrentDirectory(), "af0"), project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t0", null)][0].TaskFactoryAssemblyLoadInfo.AssemblyFile);
Assert.Equal(Path.Combine(Directory.GetCurrentDirectory(), "af1a"), project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t1", null)][0].TaskFactoryAssemblyLoadInfo.AssemblyFile);
Assert.Equal("an1", project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t1", null)][1].TaskFactoryAssemblyLoadInfo.AssemblyName);
Assert.Equal("an2", project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t2", null)][0].TaskFactoryAssemblyLoadInfo.AssemblyName);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// InitialTargets and DefaultTargets with imported projects.
/// DefaultTargets are not read from imported projects.
/// InitialTargets are gathered from imports depth-first.
/// </summary>
[Fact]
public void InitialTargetsDefaultTargets()
{
try
{
string projectFileContent = @"
<Project DefaultTargets='d0a;d0b' InitialTargets='i0a;i0b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Import Project='{0}'/>
<Import Project='{1}'/>
</Project>";
string import1Content = @"
<Project DefaultTargets='d1a;d1b' InitialTargets='i1a;i1b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Import Project='{0}'/>
</Project>";
string import2Content = @"<Project DefaultTargets='d2a;2db' InitialTargets='i2a;i2b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'/>";
string import3Content = @"<Project DefaultTargets='d3a;d3b' InitialTargets='i3a;i3b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'/>";
string import2Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import2.targets", import2Content);
string import3Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import3.targets", import3Content);
import1Content = String.Format(import1Content, import3Path);
string import1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import1.targets", import1Content);
projectFileContent = String.Format(projectFileContent, import1Path, import2Path);
ProjectInstance project = new Project(ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)))).CreateProjectInstance();
Helpers.AssertListsValueEqual(new string[] { "d0a", "d0b" }, project.DefaultTargets);
Helpers.AssertListsValueEqual(new string[] { "i0a", "i0b", "i1a", "i1b", "i3a", "i3b", "i2a", "i2b" }, project.InitialTargets);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// InitialTargets and DefaultTargets with imported projects.
/// DefaultTargets are not read from imported projects.
/// InitialTargets are gathered from imports depth-first.
/// </summary>
[Fact]
public void InitialTargetsDefaultTargetsEscaped()
{
try
{
string projectFileContent = @"
<Project DefaultTargets='d0a%3bd0b' InitialTargets='i0a%3bi0b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
</Project>";
ProjectInstance project = new Project(ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)))).CreateProjectInstance();
Helpers.AssertListsValueEqual(new string[] { "d0a;d0b" }, project.DefaultTargets);
Helpers.AssertListsValueEqual(new string[] { "i0a;i0b" }, project.InitialTargets);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// Read property group under target
/// </summary>
[Fact]
public void GetPropertyGroupUnderTarget()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t'>
<PropertyGroup Condition='c1'>
<p1 Condition='c2'>v1</p1>
<p2/>
</PropertyGroup>
</Target>
</Project>
";
ProjectInstance p = GetProjectInstance(content);
ProjectPropertyGroupTaskInstance propertyGroup = (ProjectPropertyGroupTaskInstance)(p.Targets["t"].Children[0]);
Assert.Equal("c1", propertyGroup.Condition);
List<ProjectPropertyGroupTaskPropertyInstance> properties = Helpers.MakeList(propertyGroup.Properties);
Assert.Equal(2, properties.Count);
Assert.Equal("c2", properties[0].Condition);
Assert.Equal("v1", properties[0].Value);
Assert.Equal(String.Empty, properties[1].Condition);
Assert.Equal(String.Empty, properties[1].Value);
}
/// <summary>
/// Read item group under target
/// </summary>
[Fact]
public void GetItemGroupUnderTarget()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t'>
<ItemGroup Condition='c1'>
<i Include='i1' Exclude='e1' Condition='c2'>
<m Condition='c3'>m1</m>
<n>n1</n>
</i>
<j Remove='r1'/>
<k>
<o>o1</o>
</k>
</ItemGroup>
</Target>
</Project>
";
ProjectInstance p = GetProjectInstance(content);
ProjectItemGroupTaskInstance itemGroup = (ProjectItemGroupTaskInstance)(p.Targets["t"].Children[0]);
Assert.Equal("c1", itemGroup.Condition);
List<ProjectItemGroupTaskItemInstance> items = Helpers.MakeList(itemGroup.Items);
Assert.Equal(3, items.Count);
Assert.Equal("i1", items[0].Include);
Assert.Equal("e1", items[0].Exclude);
Assert.Equal(String.Empty, items[0].Remove);
Assert.Equal("c2", items[0].Condition);
Assert.Equal(String.Empty, items[1].Include);
Assert.Equal(String.Empty, items[1].Exclude);
Assert.Equal("r1", items[1].Remove);
Assert.Equal(String.Empty, items[1].Condition);
Assert.Equal(String.Empty, items[2].Include);
Assert.Equal(String.Empty, items[2].Exclude);
Assert.Equal(String.Empty, items[2].Remove);
Assert.Equal(String.Empty, items[2].Condition);
List<ProjectItemGroupTaskMetadataInstance> metadata1 = Helpers.MakeList(items[0].Metadata);
List<ProjectItemGroupTaskMetadataInstance> metadata2 = Helpers.MakeList(items[1].Metadata);
List<ProjectItemGroupTaskMetadataInstance> metadata3 = Helpers.MakeList(items[2].Metadata);
Assert.Equal(2, metadata1.Count);
Assert.Empty(metadata2);
Assert.Single(metadata3);
Assert.Equal("c3", metadata1[0].Condition);
Assert.Equal("m1", metadata1[0].Value);
Assert.Equal(String.Empty, metadata1[1].Condition);
Assert.Equal("n1", metadata1[1].Value);
Assert.Equal(String.Empty, metadata3[0].Condition);
Assert.Equal("o1", metadata3[0].Value);
}
/// <summary>
/// Task registry accessor
/// </summary>
[Fact]
public void GetTaskRegistry()
{
ProjectInstance p = GetSampleProjectInstance();
Assert.True(p.TaskRegistry != null);
}
/// <summary>
/// Global properties accessor
/// </summary>
[Fact]
public void GetGlobalProperties()
{
ProjectInstance p = GetSampleProjectInstance();
Assert.Equal("v1", p.GlobalPropertiesDictionary["g1"].EvaluatedValue);
Assert.Equal("v2", p.GlobalPropertiesDictionary["g2"].EvaluatedValue);
}
/// <summary>
/// ToolsVersion accessor
/// </summary>
[Fact]
public void GetToolsVersion()
{
ProjectInstance p = GetSampleProjectInstance();
Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion);
}
[Fact]
public void UsingExplicitToolsVersionShouldBeFalseWhenNoToolsetIsReferencedInProject()
{
var projectInstance = new ProjectInstance(
new ProjectRootElement(
XmlReader.Create(new StringReader("<Project></Project>")), ProjectCollection.GlobalProjectCollection.ProjectRootElementCache, false, false)
);
projectInstance.UsingDifferentToolsVersionFromProjectFile.ShouldBeFalse();
}
/// <summary>
/// Toolset data is cloned properly
/// </summary>
[Fact]
public void CloneToolsetData()
{
var projectCollection = new ProjectCollection();
CreateMockToolsetIfNotExists("TESTTV", projectCollection);
ProjectInstance first = GetSampleProjectInstance(null, null, projectCollection, toolsVersion: "TESTTV");
ProjectInstance second = first.DeepCopy();
Assert.Equal(first.ToolsVersion, second.ToolsVersion);
Assert.Equal(first.ExplicitToolsVersion, second.ExplicitToolsVersion);
Assert.Equal(first.ExplicitToolsVersionSpecified, second.ExplicitToolsVersionSpecified);
}
/// <summary>
/// Test ProjectInstance's surfacing of the sub-toolset version
/// </summary>
[Fact]
public void GetSubToolsetVersion()
{
string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");
try
{
Environment.SetEnvironmentVariable("VisualStudioVersion", null);
ProjectInstance p = GetSampleProjectInstance(null, null, new ProjectCollection());
Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion);
Assert.Equal(p.Toolset.DefaultSubToolsetVersion, p.SubToolsetVersion);
if (p.Toolset.DefaultSubToolsetVersion == null)
{
Assert.Equal(MSBuildConstants.CurrentVisualStudioVersion, p.GetPropertyValue("VisualStudioVersion"));
}
else
{
Assert.Equal(p.Toolset.DefaultSubToolsetVersion, p.GetPropertyValue("VisualStudioVersion"));
}
}
finally
{
Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
}
}
/// <summary>
/// Test ProjectInstance's surfacing of the sub-toolset version when it is overridden by a value in the
/// environment
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void GetSubToolsetVersion_FromEnvironment()
{
string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");
try
{
Environment.SetEnvironmentVariable("VisualStudioVersion", "ABCD");
ProjectInstance p = GetSampleProjectInstance(null, null, new ProjectCollection());
Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion);
Assert.Equal("ABCD", p.SubToolsetVersion);
Assert.Equal("ABCD", p.GetPropertyValue("VisualStudioVersion"));
}
finally
{
Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
}
}
/// <summary>
/// Test ProjectInstance's surfacing of the sub-toolset version when it is overridden by a global property
/// </summary>
[Fact]
public void GetSubToolsetVersion_FromProjectGlobalProperties()
{
string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");
try
{
Environment.SetEnvironmentVariable("VisualStudioVersion", null);
IDictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
globalProperties.Add("VisualStudioVersion", "ABCDE");
ProjectInstance p = GetSampleProjectInstance(null, globalProperties, new ProjectCollection());
Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion);
Assert.Equal("ABCDE", p.SubToolsetVersion);
Assert.Equal("ABCDE", p.GetPropertyValue("VisualStudioVersion"));
}
finally
{
Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
}
}
/// <summary>
/// Verify that if a sub-toolset version is passed to the constructor, it all other heuristic methods for
/// getting the sub-toolset version.
/// </summary>
[Fact]
public void GetSubToolsetVersion_FromConstructor()
{
string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion");
try
{
Environment.SetEnvironmentVariable("VisualStudioVersion", "ABC");
string projectContent = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t'>
<Message Text='Hello'/>
</Target>
</Project>";
ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectContent)));
IDictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
globalProperties.Add("VisualStudioVersion", "ABCD");
IDictionary<string, string> projectCollectionGlobalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
projectCollectionGlobalProperties.Add("VisualStudioVersion", "ABCDE");
ProjectInstance p = new ProjectInstance(xml, globalProperties, ObjectModelHelpers.MSBuildDefaultToolsVersion, "ABCDEF", new ProjectCollection(projectCollectionGlobalProperties));
Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion);
Assert.Equal("ABCDEF", p.SubToolsetVersion);
Assert.Equal("ABCDEF", p.GetPropertyValue("VisualStudioVersion"));
}
finally
{
Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion);
}
}
/// <summary>
/// DefaultTargets accessor
/// </summary>
[Fact]
public void GetDefaultTargets()
{
ProjectInstance p = GetSampleProjectInstance();
Helpers.AssertListsValueEqual(new string[] { "dt" }, p.DefaultTargets);
}
/// <summary>
/// InitialTargets accessor
/// </summary>
[Fact]
public void GetInitialTargets()
{
ProjectInstance p = GetSampleProjectInstance();
Helpers.AssertListsValueEqual(new string[] { "it" }, p.InitialTargets);
}
/// <summary>
/// Cloning project clones targets
/// </summary>
[Fact]
public void CloneTargets()
{
var hostServices = new HostServices();
ProjectInstance first = GetSampleProjectInstance(hostServices);
ProjectInstance second = first.DeepCopy();
// Targets, tasks are immutable so we can expect the same objects
Assert.True(Object.ReferenceEquals(first.Targets, second.Targets));
Assert.True(Object.ReferenceEquals(first.Targets["t"], second.Targets["t"]));
var firstTasks = first.Targets["t"];
var secondTasks = second.Targets["t"];
Assert.True(Object.ReferenceEquals(firstTasks.Children[0], secondTasks.Children[0]));
}
/// <summary>
/// Cloning project copies task registry
/// </summary>
[Fact]
public void CloneTaskRegistry()
{
ProjectInstance first = GetSampleProjectInstance();
ProjectInstance second = first.DeepCopy();
// Task registry object should be immutable
Assert.Same(first.TaskRegistry, second.TaskRegistry);
}
/// <summary>
/// Cloning project copies global properties
/// </summary>
[Fact]
public void CloneGlobalProperties()
{
ProjectInstance first = GetSampleProjectInstance();
ProjectInstance second = first.DeepCopy();
Assert.Equal("v1", second.GlobalPropertiesDictionary["g1"].EvaluatedValue);
Assert.Equal("v2", second.GlobalPropertiesDictionary["g2"].EvaluatedValue);
}
/// <summary>
/// Cloning project copies default targets
/// </summary>
[Fact]
public void CloneDefaultTargets()
{
ProjectInstance first = GetSampleProjectInstance();
ProjectInstance second = first.DeepCopy();
Helpers.AssertListsValueEqual(new string[] { "dt" }, second.DefaultTargets);
}
/// <summary>
/// Cloning project copies initial targets
/// </summary>
[Fact]
public void CloneInitialTargets()
{
ProjectInstance first = GetSampleProjectInstance();
ProjectInstance second = first.DeepCopy();
Helpers.AssertListsValueEqual(new string[] { "it" }, second.InitialTargets);
}
/// <summary>
/// Cloning project copies toolsversion
/// </summary>
[Fact]
public void CloneToolsVersion()
{
ProjectInstance first = GetSampleProjectInstance();
ProjectInstance second = first.DeepCopy();
Assert.Equal(first.Toolset, second.Toolset);
}
/// <summary>
/// Cloning project copies toolsversion
/// </summary>
[Fact]
public void CloneStateTranslation()
{
ProjectInstance first = GetSampleProjectInstance();
first.TranslateEntireState = true;
ProjectInstance second = first.DeepCopy();
Assert.True(second.TranslateEntireState);
}
/// <summary>
/// Tests building a simple project and verifying the log looks as expected.
/// </summary>
[Fact]
public void Build()
{
// Setting the current directory to the MSBuild running location. It *should* be this
// already, but if it's not some other test changed it and didn't change it back. If
// the directory does not include the reference dlls the compilation will fail.
Directory.SetCurrentDirectory(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory);
string projectFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<UsingTask TaskName='Microsoft.Build.Tasks.Message' AssemblyFile='Microsoft.Build.Tasks.Core.dll'/>
<ItemGroup>
<i Include='i0'/>
</ItemGroup>
<Target Name='Build'>
<Message Text='Building...'/>
<Message Text='Completed!'/>
</Target>
</Project>";
ProjectInstance projectInstance = GetProjectInstance(projectFileContent);
List<ILogger> loggers = new List<ILogger>();
MockLogger mockLogger = new MockLogger(_output);
loggers.Add(mockLogger);
bool success = projectInstance.Build("Build", loggers);
Assert.True(success);
mockLogger.AssertLogContains(new string[] { "Building...", "Completed!" });
}
[Theory]
[InlineData(
@" <Project>
</Project>
")]
// Project with one of each direct child(indirect children trees are tested separately)
[InlineData(
@" <Project InitialTargets=`t1` DefaultTargets=`t2` ToolsVersion=`{0}`>
<UsingTask TaskName=`t1` AssemblyFile=`f1`/>
<ItemDefinitionGroup>
<i>
<n>n1</n>
</i>
</ItemDefinitionGroup>
<PropertyGroup>
<p1>v1</p1>
</PropertyGroup>
<ItemGroup>
<i Include='i0'/>
</ItemGroup>
<Target Name='t1'>
<t1/>
</Target>
<Target Name='t2' BeforeTargets=`t1`>
<t2/>
</Target>
<Target Name='t3' AfterTargets=`t2`>
<t3/>
</Target>
</Project>
")]
// Project with at least two instances of each direct child. Tests that collections serialize well.
[InlineData(
@" <Project InitialTargets=`t1` DefaultTargets=`t2` ToolsVersion=`{0}`>
<UsingTask TaskName=`t1` AssemblyFile=`f1`/>
<UsingTask TaskName=`t2` AssemblyFile=`f2`/>
<ItemDefinitionGroup>
<i>
<n>n1</n>
</i>
</ItemDefinitionGroup>
<ItemDefinitionGroup>
<i2>
<n2>n2</n2>
</i2>
</ItemDefinitionGroup>
<PropertyGroup>
<p1>v1</p1>
</PropertyGroup>
<PropertyGroup>
<p2>v2</p2>
</PropertyGroup>
<ItemGroup>
<i Include='i1'/>
</ItemGroup>
<ItemGroup>
<i2 Include='i2'>
<m1 Condition=`1==1`>m1</m1>
<m2>m2</m2>
</i2>
</ItemGroup>
<Target Name='t1'>
<t1/>
</Target>
<Target Name='t2' BeforeTargets=`t1`>
<t2/>
</Target>
<Target Name='t3' AfterTargets=`t1`>
<t3/>
</Target>
<Target Name='t4' BeforeTargets=`t1`>
<t4/>
</Target>
<Target Name='t5' AfterTargets=`t1`>
<t5/>
</Target>
</Project>
")]
public void ProjectInstanceCanSerializeEntireStateViaTranslator(string projectContents)
{
projectContents = string.Format(projectContents, MSBuildConstants.CurrentToolsVersion);
var original = new ProjectInstance(ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(projectContents)))));
original.TranslateEntireState = true;
((ITranslatable) original).Translate(TranslationHelpers.GetWriteTranslator());
var copy = ProjectInstance.FactoryForDeserialization(TranslationHelpers.GetReadTranslator());
Assert.Equal(original, copy, new ProjectInstanceComparer());
}
public delegate ProjectInstance ProjectInstanceFactory(string file, ProjectRootElement xml, ProjectCollection collection);
public static IEnumerable<object[]> ProjectInstanceHasEvaluationIdTestData()
{
// from file
yield return new ProjectInstanceFactory[]
{
(f, xml, c) => new ProjectInstance(f, null, null, c)
};
// from Project
yield return new ProjectInstanceFactory[]
{
(f, xml, c) => new Project(f, null, null, c).CreateProjectInstance()
};
// from DeepCopy
yield return new ProjectInstanceFactory[]
{
(f, xml, c) => new ProjectInstance(f, null, null, c).DeepCopy()
};
// from ProjectRootElement
yield return new ProjectInstanceFactory[]
{
(f, xml, c) => new ProjectInstance(xml, null, null, c).DeepCopy()
};
// from translated project instance
yield return new ProjectInstanceFactory[]
{
(f, xml, c) =>
{
var pi = new ProjectInstance(f, null, null, c);
pi.AddItem("foo", "bar");
pi.TranslateEntireState = true;
((ITranslatable) pi).Translate(TranslationHelpers.GetWriteTranslator());
var copy = ProjectInstance.FactoryForDeserialization(TranslationHelpers.GetReadTranslator());
return copy;
}
};
}
[Theory]
[MemberData(nameof(ProjectInstanceHasEvaluationIdTestData))]
public void ProjectInstanceHasEvaluationId(ProjectInstanceFactory projectInstanceFactory)
{
using (var env = TestEnvironment.Create())
{
var file = env.CreateFile().Path;
var projectCollection = env.CreateProjectCollection().Collection;
var xml = ProjectRootElement.Create(projectCollection);
xml.Save(file);
var projectInstance = projectInstanceFactory.Invoke(file, xml, projectCollection);
Assert.NotEqual(BuildEventContext.InvalidEvaluationId, projectInstance.EvaluationId);
}
}
/// <summary>
/// Create a ProjectInstance from provided project content
/// </summary>
private static ProjectInstance GetProjectInstance(string content)
{
return GetProjectInstance(content, null);
}
/// <summary>
/// Create a ProjectInstance from provided project content and host services object
/// </summary>
private static ProjectInstance GetProjectInstance(string content, HostServices hostServices)
{
return GetProjectInstance(content, hostServices, null, null);
}
/// <summary>
/// Create a ProjectInstance from provided project content and host services object
/// </summary>
private static ProjectInstance GetProjectInstance(string content, HostServices hostServices, IDictionary<string, string> globalProperties, ProjectCollection projectCollection, string toolsVersion = null)
{
XmlReader reader = XmlReader.Create(new StringReader(content));
if (globalProperties == null)
{
// choose some interesting defaults if we weren't explicitly asked to use a set.
globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
globalProperties.Add("g1", "v1");
globalProperties.Add("g2", "v2");
}
Project project = new Project(reader, globalProperties, toolsVersion ?? ObjectModelHelpers.MSBuildDefaultToolsVersion, projectCollection ?? ProjectCollection.GlobalProjectCollection);
ProjectInstance instance = project.CreateProjectInstance();
return instance;
}
/// <summary>
/// Create a ProjectInstance with some items and properties and targets
/// </summary>
private static ProjectInstance GetSampleProjectInstance()
{
return GetSampleProjectInstance(null);
}
/// <summary>
/// Create a ProjectInstance with some items and properties and targets
/// </summary>
private static ProjectInstance GetSampleProjectInstance(HostServices hostServices)
{
return GetSampleProjectInstance(hostServices, null, null);
}
/// <summary>
/// Create a ProjectInstance with some items and properties and targets
/// </summary>
private static ProjectInstance GetSampleProjectInstance(HostServices hostServices, IDictionary<string, string> globalProperties, ProjectCollection projectCollection, string toolsVersion = null)
{
string toolsVersionSubstring = toolsVersion != null ? "ToolsVersion=\"" + toolsVersion + "\" " : String.Empty;
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' InitialTargets='it' DefaultTargets='dt' " + toolsVersionSubstring + @">
<PropertyGroup>
<p1>v1</p1>
<p2>v2</p2>
<p2>$(p2)X$(p)</p2>
</PropertyGroup>
<ItemGroup>
<i Include='i0'/>
<i Include='i1'>
<m>m1</m>
</i>
<i Include='$(p1)'/>
</ItemGroup>
<Target Name='t'>
<t1 a='a1' b='b1' ContinueOnError='coe' Condition='c'/>
<t2/>
</Target>
<Target Name='tt'/>
</Project>
";
ProjectInstance p = GetProjectInstance(content, hostServices, globalProperties, projectCollection, toolsVersion);
return p;
}
/// <summary>
/// Creates a toolset with the given tools version if one does not already exist.
/// </summary>
private static void CreateMockToolsetIfNotExists(string toolsVersion, ProjectCollection projectCollection)
{
ProjectCollection pc = projectCollection;
if (!pc.Toolsets.Any(t => String.Equals(t.ToolsVersion, toolsVersion, StringComparison.OrdinalIgnoreCase)))
{
Toolset template = pc.Toolsets.First(t => String.Equals(t.ToolsVersion, pc.DefaultToolsVersion, StringComparison.OrdinalIgnoreCase));
var toolset = new Toolset(
toolsVersion,
template.ToolsPath,
template.Properties.ToDictionary(p => p.Key, p => p.Value.EvaluatedValue),
pc,
null);
pc.AddToolset(toolset);
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
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>
/// VirtualNetworksOperations operations.
/// </summary>
internal partial class VirtualNetworksOperations : IServiceOperations<NetworkClient>, IVirtualNetworksOperations
{
/// <summary>
/// Initializes a new instance of the VirtualNetworksOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VirtualNetworksOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified virtual network by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </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<VirtualNetwork>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
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("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("expand", expand);
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.Network/virtualNetworks/{virtualNetworkName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_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 (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
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 = Microsoft.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<VirtualNetwork>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetwork>(_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>
/// Creates or updates a virtual network in the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<VirtualNetwork>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<VirtualNetwork> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all virtual networks in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
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("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworks").ToString();
_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 = Microsoft.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<VirtualNetwork>>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all virtual networks in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </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<VirtualNetwork>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
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("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", 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.Network/virtualNetworks").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_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 = Microsoft.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<VirtualNetwork>>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_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>
/// Checks whether a private IP address is available for use.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='ipAddress'>
/// The private IP address to be verified.
/// </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<IPAddressAvailabilityResult>> CheckIPAddressAvailabilityWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string ipAddress = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
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("ipAddress", ipAddress);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CheckIPAddressAvailability", 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.Network/virtualNetworks/{virtualNetworkName}/CheckIPAddressAvailability").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (ipAddress != null)
{
_queryParameters.Add(string.Format("ipAddress={0}", System.Uri.EscapeDataString(ipAddress)));
}
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 = Microsoft.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<IPAddressAvailabilityResult>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<IPAddressAvailabilityResult>(_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 virtual network.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
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("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", 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.Network/virtualNetworks/{virtualNetworkName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_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 != 202 && (int)_statusCode != 204 && (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 = Microsoft.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>
/// Creates or updates a virtual network in the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network 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<VirtualNetwork>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (virtualNetworkName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
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("virtualNetworkName", virtualNetworkName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", 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.Network/virtualNetworks/{virtualNetworkName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName));
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.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<VirtualNetwork>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all virtual networks in a subscription.
/// </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<VirtualNetwork>>> ListAllNextWithHttpMessagesAsync(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, "ListAllNext", 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 = Microsoft.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<VirtualNetwork>>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all virtual networks in a resource group.
/// </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<VirtualNetwork>>> ListNextWithHttpMessagesAsync(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, "ListNext", 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 = Microsoft.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<VirtualNetwork>>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_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) 2008-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;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnit.Framework
{
/// <summary>
/// Supplies a set of random values to a single parameter of a parameterized test.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public class RandomAttribute : NUnitAttribute, IParameterDataSource
{
private RandomDataSource _source;
private readonly int _count;
/// <summary>
/// If true, no value will be repeated.
/// </summary>
public bool Distinct { get; set; }
#region Constructors
/// <summary>
/// Construct a random set of values appropriate for the Type of the
/// parameter on which the attribute appears, specifying only the count.
/// </summary>
/// <param name="count"></param>
public RandomAttribute(int count)
{
_count = count;
}
/// <summary>
/// Construct a set of ints within a specified range
/// </summary>
public RandomAttribute(int min, int max, int count)
{
_source = new IntDataSource(min, max, count);
}
/// <summary>
/// Construct a set of unsigned ints within a specified range
/// </summary>
[CLSCompliant(false)]
public RandomAttribute(uint min, uint max, int count)
{
_source = new UIntDataSource(min, max, count);
}
/// <summary>
/// Construct a set of longs within a specified range
/// </summary>
public RandomAttribute(long min, long max, int count)
{
_source = new LongDataSource(min, max, count);
}
/// <summary>
/// Construct a set of unsigned longs within a specified range
/// </summary>
[CLSCompliant(false)]
public RandomAttribute(ulong min, ulong max, int count)
{
_source = new ULongDataSource(min, max, count);
}
/// <summary>
/// Construct a set of shorts within a specified range
/// </summary>
public RandomAttribute(short min, short max, int count)
{
_source = new ShortDataSource(min, max, count);
}
/// <summary>
/// Construct a set of unsigned shorts within a specified range
/// </summary>
[CLSCompliant(false)]
public RandomAttribute(ushort min, ushort max, int count)
{
_source = new UShortDataSource(min, max, count);
}
/// <summary>
/// Construct a set of doubles within a specified range
/// </summary>
public RandomAttribute(double min, double max, int count)
{
_source = new DoubleDataSource(min, max, count);
}
/// <summary>
/// Construct a set of floats within a specified range
/// </summary>
public RandomAttribute(float min, float max, int count)
{
_source = new FloatDataSource(min, max, count);
}
/// <summary>
/// Construct a set of bytes within a specified range
/// </summary>
public RandomAttribute(byte min, byte max, int count)
{
_source = new ByteDataSource(min, max, count);
}
/// <summary>
/// Construct a set of sbytes within a specified range
/// </summary>
[CLSCompliant(false)]
public RandomAttribute(sbyte min, sbyte max, int count)
{
_source = new SByteDataSource(min, max, count);
}
#endregion
#region IParameterDataSource Interface
/// <summary>
/// Retrieves a list of arguments which can be passed to the specified parameter.
/// </summary>
/// <param name="parameter">The parameter of a parameterized test.</param>
public IEnumerable GetData(IParameterInfo parameter)
{
// Since a separate Randomizer is used for each parameter,
// we can't fill in the data in the constructor of the
// attribute. Only now, when GetData is called, do we have
// sufficient information to create the values in a
// repeatable manner.
Type parmType = parameter.ParameterType;
if (_source == null)
{
if (parmType == typeof(int))
_source = new IntDataSource(_count);
else if (parmType == typeof(uint))
_source = new UIntDataSource(_count);
else if (parmType == typeof(long))
_source = new LongDataSource(_count);
else if (parmType == typeof(ulong))
_source = new ULongDataSource(_count);
else if (parmType == typeof(short))
_source = new ShortDataSource(_count);
else if (parmType == typeof(ushort))
_source = new UShortDataSource(_count);
else if (parmType == typeof(double))
_source = new DoubleDataSource(_count);
else if (parmType == typeof(float))
_source = new FloatDataSource(_count);
else if (parmType == typeof(byte))
_source = new ByteDataSource(_count);
else if (parmType == typeof(sbyte))
_source = new SByteDataSource(_count);
else if (parmType == typeof(decimal))
_source = new DecimalDataSource(_count);
else if (parmType.GetTypeInfo().IsEnum)
_source = new EnumDataSource(_count);
else // Default
_source = new IntDataSource(_count);
}
else if (_source.DataType != parmType && WeConvert(_source.DataType, parmType))
{
_source.Distinct = Distinct;
_source = new RandomDataConverter(_source);
}
_source.Distinct = Distinct;
return _source.GetData(parameter);
}
private bool WeConvert(Type sourceType, Type targetType)
{
if (targetType == typeof(short) || targetType == typeof(ushort) || targetType == typeof(byte) || targetType == typeof(sbyte))
return sourceType == typeof(int);
if (targetType == typeof(decimal))
return sourceType == typeof(int) || sourceType == typeof(double);
return false;
}
#endregion
#region Nested DataSource Classes
#region RandomDataSource
abstract class RandomDataSource : IParameterDataSource
{
public Type DataType { get; protected set; }
public bool Distinct { get; set; }
public abstract IEnumerable GetData(IParameterInfo parameter);
}
abstract class RandomDataSource<T> : RandomDataSource
{
private readonly T _min;
private readonly T _max;
private readonly int _count;
private readonly bool _inRange;
private readonly List<T> previousValues = new List<T>();
protected Randomizer _randomizer;
protected RandomDataSource(int count)
{
_count = count;
_inRange = false;
DataType = typeof(T);
}
protected RandomDataSource(T min, T max, int count)
{
_min = min;
_max = max;
_count = count;
_inRange = true;
DataType = typeof(T);
}
public override IEnumerable GetData(IParameterInfo parameter)
{
//Guard.ArgumentValid(parameter.ParameterType == typeof(T), "Parameter type must be " + typeof(T).Name, "parameter");
_randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo);
Guard.OperationValid(!(Distinct && _inRange && !CanBeDistinct(_min, _max, _count)), $"The range of values is [{_min}, {_max}[ and the random value count is {_count} so the values cannot be distinct.");
for (int i = 0; i < _count; i++)
{
if (Distinct)
{
T next;
do
{
next = _inRange
? GetNext(_min, _max)
: GetNext();
} while (previousValues.Contains(next));
previousValues.Add(next);
yield return next;
}
else
yield return _inRange
? GetNext(_min, _max)
: GetNext();
}
}
protected abstract T GetNext();
protected abstract T GetNext(T min, T max);
protected abstract bool CanBeDistinct(T min, T max, int count);
}
#endregion
#region RandomDataConverter
class RandomDataConverter : RandomDataSource
{
readonly IParameterDataSource _source;
public RandomDataConverter(IParameterDataSource source)
{
_source = source;
}
public override IEnumerable GetData(IParameterInfo parameter)
{
Type parmType = parameter.ParameterType;
foreach (object obj in _source.GetData(parameter))
{
if (obj is int)
{
int ival = (int)obj; // unbox first
if (parmType == typeof(short))
yield return (short)ival;
else if (parmType == typeof(ushort))
yield return (ushort)ival;
else if (parmType == typeof(byte))
yield return (byte)ival;
else if (parmType == typeof(sbyte))
yield return (sbyte)ival;
else if (parmType == typeof(decimal))
yield return (decimal)ival;
}
else if (obj is double)
{
double d = (double)obj; // unbox first
if (parmType == typeof(decimal))
yield return (decimal)d;
}
}
}
}
#endregion
#region IntDataSource
class IntDataSource : RandomDataSource<int>
{
public IntDataSource(int count) : base(count) { }
public IntDataSource(int min, int max, int count) : base(min, max, count) { }
protected override int GetNext()
{
return _randomizer.Next();
}
protected override int GetNext(int min, int max)
{
return _randomizer.Next(min, max);
}
protected override bool CanBeDistinct(int min, int max, int count)
{
return count <= max - min;
}
}
#endregion
#region UIntDataSource
class UIntDataSource : RandomDataSource<uint>
{
public UIntDataSource(int count) : base(count) { }
public UIntDataSource(uint min, uint max, int count) : base(min, max, count) { }
protected override uint GetNext()
{
return _randomizer.NextUInt();
}
protected override uint GetNext(uint min, uint max)
{
return _randomizer.NextUInt(min, max);
}
protected override bool CanBeDistinct(uint min, uint max, int count)
{
return count <= max - min;
}
}
#endregion
#region LongDataSource
class LongDataSource : RandomDataSource<long>
{
public LongDataSource(int count) : base(count) { }
public LongDataSource(long min, long max, int count) : base(min, max, count) { }
protected override long GetNext()
{
return _randomizer.NextLong();
}
protected override long GetNext(long min, long max)
{
return _randomizer.NextLong(min, max);
}
protected override bool CanBeDistinct(long min, long max, int count)
{
return count <= max - min;
}
}
#endregion
#region ULongDataSource
class ULongDataSource : RandomDataSource<ulong>
{
public ULongDataSource(int count) : base(count) { }
public ULongDataSource(ulong min, ulong max, int count) : base(min, max, count) { }
protected override ulong GetNext()
{
return _randomizer.NextULong();
}
protected override ulong GetNext(ulong min, ulong max)
{
return _randomizer.NextULong(min, max);
}
protected override bool CanBeDistinct(ulong min, ulong max, int count)
{
return (uint)count <= max - min;
}
}
#endregion
#region ShortDataSource
class ShortDataSource : RandomDataSource<short>
{
public ShortDataSource(int count) : base(count) { }
public ShortDataSource(short min, short max, int count) : base(min, max, count) { }
protected override short GetNext()
{
return _randomizer.NextShort();
}
protected override short GetNext(short min, short max)
{
return _randomizer.NextShort(min, max);
}
protected override bool CanBeDistinct(short min, short max, int count)
{
return count <= max - min;
}
}
#endregion
#region UShortDataSource
class UShortDataSource : RandomDataSource<ushort>
{
public UShortDataSource(int count) : base(count) { }
public UShortDataSource(ushort min, ushort max, int count) : base(min, max, count) { }
protected override ushort GetNext()
{
return _randomizer.NextUShort();
}
protected override ushort GetNext(ushort min, ushort max)
{
return _randomizer.NextUShort(min, max);
}
protected override bool CanBeDistinct(ushort min, ushort max, int count)
{
return count <= max - min;
}
}
#endregion
#region DoubleDataSource
class DoubleDataSource : RandomDataSource<double>
{
public DoubleDataSource(int count) : base(count) { }
public DoubleDataSource(double min, double max, int count) : base(min, max, count) { }
protected override double GetNext()
{
return _randomizer.NextDouble();
}
protected override double GetNext(double min, double max)
{
return _randomizer.NextDouble(min, max);
}
protected override bool CanBeDistinct(double min, double max, int count)
{
return true;
}
}
#endregion
#region FloatDataSource
class FloatDataSource : RandomDataSource<float>
{
public FloatDataSource(int count) : base(count) { }
public FloatDataSource(float min, float max, int count) : base(min, max, count) { }
protected override float GetNext()
{
return _randomizer.NextFloat();
}
protected override float GetNext(float min, float max)
{
return _randomizer.NextFloat(min, max);
}
protected override bool CanBeDistinct(float min, float max, int count)
{
return true;
}
}
#endregion
#region ByteDataSource
class ByteDataSource : RandomDataSource<byte>
{
public ByteDataSource(int count) : base(count) { }
public ByteDataSource(byte min, byte max, int count) : base(min, max, count) { }
protected override byte GetNext()
{
return _randomizer.NextByte();
}
protected override byte GetNext(byte min, byte max)
{
return _randomizer.NextByte(min, max);
}
protected override bool CanBeDistinct(byte min, byte max, int count)
{
return count <= max - min;
}
}
#endregion
#region SByteDataSource
class SByteDataSource : RandomDataSource<sbyte>
{
public SByteDataSource(int count) : base(count) { }
public SByteDataSource(sbyte min, sbyte max, int count) : base(min, max, count) { }
protected override sbyte GetNext()
{
return _randomizer.NextSByte();
}
protected override sbyte GetNext(sbyte min, sbyte max)
{
return _randomizer.NextSByte(min, max);
}
protected override bool CanBeDistinct(sbyte min, sbyte max, int count)
{
return count <= max - min;
}
}
#endregion
#region EnumDataSource
class EnumDataSource : RandomDataSource
{
private readonly int _count;
private readonly List<object> previousValues = new List<object>();
public EnumDataSource(int count)
{
_count = count;
DataType = typeof(Enum);
}
public override IEnumerable GetData(IParameterInfo parameter)
{
Guard.ArgumentValid(parameter.ParameterType.GetTypeInfo().IsEnum, "EnumDataSource requires an enum parameter", nameof(parameter));
Randomizer randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo);
DataType = parameter.ParameterType;
int valueCount = Enum.GetValues(DataType).Cast<int>().Distinct().Count();
Guard.OperationValid(!(Distinct && _count > valueCount), $"The enum \"{DataType.Name}\" has {valueCount} values and the random value count is {_count} so the values cannot be distinct.");
for (int i = 0; i < _count; i++)
{
if (Distinct)
{
object next;
do
{
next = randomizer.NextEnum(parameter.ParameterType);
} while (previousValues.Contains(next));
previousValues.Add(next);
yield return next;
}
else
yield return randomizer.NextEnum(parameter.ParameterType);
}
}
}
#endregion
#region DecimalDataSource
// Currently, Randomizer doesn't implement methods for decimal
// so we use random Ulongs and convert them. This doesn't cover
// the full range of decimal, so it's temporary.
class DecimalDataSource : RandomDataSource<decimal>
{
public DecimalDataSource(int count) : base(count) { }
public DecimalDataSource(decimal min, decimal max, int count) : base(min, max, count) { }
protected override decimal GetNext()
{
return _randomizer.NextDecimal();
}
protected override decimal GetNext(decimal min, decimal max)
{
return _randomizer.NextDecimal(min, max);
}
protected override bool CanBeDistinct(decimal min, decimal max, int count)
{
return true;
}
}
#endregion
#endregion
}
}
| |
namespace UnityEngine.PostProcessing
{
using DebugMode = BuiltinDebugViewsModel.Mode;
public sealed class ColorGradingComponent : PostProcessingComponentRenderTexture<ColorGradingModel>
{
static class Uniforms
{
internal static readonly int _LutParams = Shader.PropertyToID("_LutParams");
internal static readonly int _NeutralTonemapperParams1 = Shader.PropertyToID("_NeutralTonemapperParams1");
internal static readonly int _NeutralTonemapperParams2 = Shader.PropertyToID("_NeutralTonemapperParams2");
internal static readonly int _HueShift = Shader.PropertyToID("_HueShift");
internal static readonly int _Saturation = Shader.PropertyToID("_Saturation");
internal static readonly int _Contrast = Shader.PropertyToID("_Contrast");
internal static readonly int _Balance = Shader.PropertyToID("_Balance");
internal static readonly int _Lift = Shader.PropertyToID("_Lift");
internal static readonly int _InvGamma = Shader.PropertyToID("_InvGamma");
internal static readonly int _Gain = Shader.PropertyToID("_Gain");
internal static readonly int _Slope = Shader.PropertyToID("_Slope");
internal static readonly int _Power = Shader.PropertyToID("_Power");
internal static readonly int _Offset = Shader.PropertyToID("_Offset");
internal static readonly int _ChannelMixerRed = Shader.PropertyToID("_ChannelMixerRed");
internal static readonly int _ChannelMixerGreen = Shader.PropertyToID("_ChannelMixerGreen");
internal static readonly int _ChannelMixerBlue = Shader.PropertyToID("_ChannelMixerBlue");
internal static readonly int _Curves = Shader.PropertyToID("_Curves");
internal static readonly int _LogLut = Shader.PropertyToID("_LogLut");
internal static readonly int _LogLut_Params = Shader.PropertyToID("_LogLut_Params");
internal static readonly int _ExposureEV = Shader.PropertyToID("_ExposureEV");
}
const int k_InternalLogLutSize = 32;
const int k_CurvePrecision = 128;
const float k_CurveStep = 1f / k_CurvePrecision;
Texture2D m_GradingCurves;
Color[] m_pixels = new Color[k_CurvePrecision * 2];
public override bool active
{
get
{
return model.enabled
&& !context.interrupted;
}
}
// An analytical model of chromaticity of the standard illuminant, by Judd et al.
// http://en.wikipedia.org/wiki/Standard_illuminant#Illuminant_series_D
// Slightly modifed to adjust it with the D65 white point (x=0.31271, y=0.32902).
float StandardIlluminantY(float x)
{
return 2.87f * x - 3f * x * x - 0.27509507f;
}
// CIE xy chromaticity to CAT02 LMS.
// http://en.wikipedia.org/wiki/LMS_color_space#CAT02
Vector3 CIExyToLMS(float x, float y)
{
float Y = 1f;
float X = Y * x / y;
float Z = Y * (1f - x - y) / y;
float L = 0.7328f * X + 0.4296f * Y - 0.1624f * Z;
float M = -0.7036f * X + 1.6975f * Y + 0.0061f * Z;
float S = 0.0030f * X + 0.0136f * Y + 0.9834f * Z;
return new Vector3(L, M, S);
}
Vector3 CalculateColorBalance(float temperature, float tint)
{
// Range ~[-1.8;1.8] ; using higher ranges is unsafe
float t1 = temperature / 55f;
float t2 = tint / 55f;
// Get the CIE xy chromaticity of the reference white point.
// Note: 0.31271 = x value on the D65 white point
float x = 0.31271f - t1 * (t1 < 0f ? 0.1f : 0.05f);
float y = StandardIlluminantY(x) + t2 * 0.05f;
// Calculate the coefficients in the LMS space.
var w1 = new Vector3(0.949237f, 1.03542f, 1.08728f); // D65 white point
var w2 = CIExyToLMS(x, y);
return new Vector3(w1.x / w2.x, w1.y / w2.y, w1.z / w2.z);
}
static Color NormalizeColor(Color c)
{
float sum = (c.r + c.g + c.b) / 3f;
if (Mathf.Approximately(sum, 0f))
return new Color(1f, 1f, 1f, c.a);
return new Color
{
r = c.r / sum,
g = c.g / sum,
b = c.b / sum,
a = c.a
};
}
static Vector3 ClampVector(Vector3 v, float min, float max)
{
return new Vector3(
Mathf.Clamp(v.x, min, max),
Mathf.Clamp(v.y, min, max),
Mathf.Clamp(v.z, min, max)
);
}
public static Vector3 GetLiftValue(Color lift)
{
const float kLiftScale = 0.1f;
var nLift = NormalizeColor(lift);
float avgLift = (nLift.r + nLift.g + nLift.b) / 3f;
// Getting some artifacts when going into the negatives using a very low offset (lift.a) with non ACES-tonemapping
float liftR = (nLift.r - avgLift) * kLiftScale + lift.a;
float liftG = (nLift.g - avgLift) * kLiftScale + lift.a;
float liftB = (nLift.b - avgLift) * kLiftScale + lift.a;
return ClampVector(new Vector3(liftR, liftG, liftB), -1f, 1f);
}
public static Vector3 GetGammaValue(Color gamma)
{
const float kGammaScale = 0.5f;
const float kMinGamma = 0.01f;
var nGamma = NormalizeColor(gamma);
float avgGamma = (nGamma.r + nGamma.g + nGamma.b) / 3f;
gamma.a *= gamma.a < 0f ? 0.8f : 5f;
float gammaR = Mathf.Pow(2f, (nGamma.r - avgGamma) * kGammaScale) + gamma.a;
float gammaG = Mathf.Pow(2f, (nGamma.g - avgGamma) * kGammaScale) + gamma.a;
float gammaB = Mathf.Pow(2f, (nGamma.b - avgGamma) * kGammaScale) + gamma.a;
float invGammaR = 1f / Mathf.Max(kMinGamma, gammaR);
float invGammaG = 1f / Mathf.Max(kMinGamma, gammaG);
float invGammaB = 1f / Mathf.Max(kMinGamma, gammaB);
return ClampVector(new Vector3(invGammaR, invGammaG, invGammaB), 0f, 5f);
}
public static Vector3 GetGainValue(Color gain)
{
const float kGainScale = 0.5f;
var nGain = NormalizeColor(gain);
float avgGain = (nGain.r + nGain.g + nGain.b) / 3f;
gain.a *= gain.a > 0f ? 3f : 1f;
float gainR = Mathf.Pow(2f, (nGain.r - avgGain) * kGainScale) + gain.a;
float gainG = Mathf.Pow(2f, (nGain.g - avgGain) * kGainScale) + gain.a;
float gainB = Mathf.Pow(2f, (nGain.b - avgGain) * kGainScale) + gain.a;
return ClampVector(new Vector3(gainR, gainG, gainB), 0f, 4f);
}
public static void CalculateLiftGammaGain(Color lift, Color gamma, Color gain, out Vector3 outLift, out Vector3 outGamma, out Vector3 outGain)
{
outLift = GetLiftValue(lift);
outGamma = GetGammaValue(gamma);
outGain = GetGainValue(gain);
}
public static Vector3 GetSlopeValue(Color slope)
{
const float kSlopeScale = 0.1f;
var nSlope = NormalizeColor(slope);
float avgSlope = (nSlope.r + nSlope.g + nSlope.b) / 3f;
slope.a *= 0.5f;
float slopeR = (nSlope.r - avgSlope) * kSlopeScale + slope.a + 1f;
float slopeG = (nSlope.g - avgSlope) * kSlopeScale + slope.a + 1f;
float slopeB = (nSlope.b - avgSlope) * kSlopeScale + slope.a + 1f;
return ClampVector(new Vector3(slopeR, slopeG, slopeB), 0f, 2f);
}
public static Vector3 GetPowerValue(Color power)
{
const float kPowerScale = 0.1f;
const float minPower = 0.01f;
var nPower = NormalizeColor(power);
float avgPower = (nPower.r + nPower.g + nPower.b) / 3f;
power.a *= 0.5f;
float powerR = (nPower.r - avgPower) * kPowerScale + power.a + 1f;
float powerG = (nPower.g - avgPower) * kPowerScale + power.a + 1f;
float powerB = (nPower.b - avgPower) * kPowerScale + power.a + 1f;
float invPowerR = 1f / Mathf.Max(minPower, powerR);
float invPowerG = 1f / Mathf.Max(minPower, powerG);
float invPowerB = 1f / Mathf.Max(minPower, powerB);
return ClampVector(new Vector3(invPowerR, invPowerG, invPowerB), 0.5f, 2.5f);
}
public static Vector3 GetOffsetValue(Color offset)
{
const float kOffsetScale = 0.05f;
var nOffset = NormalizeColor(offset);
float avgOffset = (nOffset.r + nOffset.g + nOffset.b) / 3f;
offset.a *= 0.5f;
float offsetR = (nOffset.r - avgOffset) * kOffsetScale + offset.a;
float offsetG = (nOffset.g - avgOffset) * kOffsetScale + offset.a;
float offsetB = (nOffset.b - avgOffset) * kOffsetScale + offset.a;
return ClampVector(new Vector3(offsetR, offsetG, offsetB), -0.8f, 0.8f);
}
public static void CalculateSlopePowerOffset(Color slope, Color power, Color offset, out Vector3 outSlope, out Vector3 outPower, out Vector3 outOffset)
{
outSlope = GetSlopeValue(slope);
outPower = GetPowerValue(power);
outOffset = GetOffsetValue(offset);
}
TextureFormat GetCurveFormat()
{
if (SystemInfo.SupportsTextureFormat(TextureFormat.RGBAHalf))
return TextureFormat.RGBAHalf;
return TextureFormat.RGBA32;
}
Texture2D GetCurveTexture()
{
if (m_GradingCurves == null)
{
m_GradingCurves = new Texture2D(k_CurvePrecision, 2, GetCurveFormat(), false, true)
{
name = "Internal Curves Texture",
hideFlags = HideFlags.DontSave,
anisoLevel = 0,
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear
};
}
var curves = model.settings.curves;
curves.hueVShue.Cache();
curves.hueVSsat.Cache();
for (int i = 0; i < k_CurvePrecision; i++)
{
float t = i * k_CurveStep;
// HSL
float x = curves.hueVShue.Evaluate(t);
float y = curves.hueVSsat.Evaluate(t);
float z = curves.satVSsat.Evaluate(t);
float w = curves.lumVSsat.Evaluate(t);
m_pixels[i] = new Color(x, y, z, w);
// YRGB
float m = curves.master.Evaluate(t);
float r = curves.red.Evaluate(t);
float g = curves.green.Evaluate(t);
float b = curves.blue.Evaluate(t);
m_pixels[i + k_CurvePrecision] = new Color(r, g, b, m);
}
m_GradingCurves.SetPixels(m_pixels);
m_GradingCurves.Apply(false, false);
return m_GradingCurves;
}
bool IsLogLutValid(RenderTexture lut)
{
return lut != null && lut.IsCreated() && lut.height == k_InternalLogLutSize;
}
RenderTextureFormat GetLutFormat()
{
if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf))
return RenderTextureFormat.ARGBHalf;
return RenderTextureFormat.ARGB32;
}
void GenerateLut()
{
var settings = model.settings;
if (!IsLogLutValid(model.bakedLut))
{
GraphicsUtils.Destroy(model.bakedLut);
model.bakedLut = new RenderTexture(k_InternalLogLutSize * k_InternalLogLutSize, k_InternalLogLutSize, 0, GetLutFormat())
{
name = "Color Grading Log LUT",
hideFlags = HideFlags.DontSave,
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp,
anisoLevel = 0
};
}
var lutMaterial = context.materialFactory.Get("Hidden/Post FX/Lut Generator");
lutMaterial.SetVector(Uniforms._LutParams, new Vector4(
k_InternalLogLutSize,
0.5f / (k_InternalLogLutSize * k_InternalLogLutSize),
0.5f / k_InternalLogLutSize,
k_InternalLogLutSize / (k_InternalLogLutSize - 1f))
);
// Tonemapping
lutMaterial.shaderKeywords = null;
var tonemapping = settings.tonemapping;
switch (tonemapping.tonemapper)
{
case ColorGradingModel.Tonemapper.Neutral:
{
lutMaterial.EnableKeyword("TONEMAPPING_NEUTRAL");
const float scaleFactor = 20f;
const float scaleFactorHalf = scaleFactor * 0.5f;
float inBlack = tonemapping.neutralBlackIn * scaleFactor + 1f;
float outBlack = tonemapping.neutralBlackOut * scaleFactorHalf + 1f;
float inWhite = tonemapping.neutralWhiteIn / scaleFactor;
float outWhite = 1f - tonemapping.neutralWhiteOut / scaleFactor;
float blackRatio = inBlack / outBlack;
float whiteRatio = inWhite / outWhite;
const float a = 0.2f;
float b = Mathf.Max(0f, Mathf.LerpUnclamped(0.57f, 0.37f, blackRatio));
float c = Mathf.LerpUnclamped(0.01f, 0.24f, whiteRatio);
float d = Mathf.Max(0f, Mathf.LerpUnclamped(0.02f, 0.20f, blackRatio));
const float e = 0.02f;
const float f = 0.30f;
lutMaterial.SetVector(Uniforms._NeutralTonemapperParams1, new Vector4(a, b, c, d));
lutMaterial.SetVector(Uniforms._NeutralTonemapperParams2, new Vector4(e, f, tonemapping.neutralWhiteLevel, tonemapping.neutralWhiteClip / scaleFactorHalf));
break;
}
case ColorGradingModel.Tonemapper.ACES:
{
lutMaterial.EnableKeyword("TONEMAPPING_FILMIC");
break;
}
}
// Color balance & basic grading settings
lutMaterial.SetFloat(Uniforms._HueShift, settings.basic.hueShift / 360f);
lutMaterial.SetFloat(Uniforms._Saturation, settings.basic.saturation);
lutMaterial.SetFloat(Uniforms._Contrast, settings.basic.contrast);
lutMaterial.SetVector(Uniforms._Balance, CalculateColorBalance(settings.basic.temperature, settings.basic.tint));
// Lift / Gamma / Gain
Vector3 lift, gamma, gain;
CalculateLiftGammaGain(
settings.colorWheels.linear.lift,
settings.colorWheels.linear.gamma,
settings.colorWheels.linear.gain,
out lift, out gamma, out gain
);
lutMaterial.SetVector(Uniforms._Lift, lift);
lutMaterial.SetVector(Uniforms._InvGamma, gamma);
lutMaterial.SetVector(Uniforms._Gain, gain);
// Slope / Power / Offset
Vector3 slope, power, offset;
CalculateSlopePowerOffset(
settings.colorWheels.log.slope,
settings.colorWheels.log.power,
settings.colorWheels.log.offset,
out slope, out power, out offset
);
lutMaterial.SetVector(Uniforms._Slope, slope);
lutMaterial.SetVector(Uniforms._Power, power);
lutMaterial.SetVector(Uniforms._Offset, offset);
// Channel mixer
lutMaterial.SetVector(Uniforms._ChannelMixerRed, settings.channelMixer.red);
lutMaterial.SetVector(Uniforms._ChannelMixerGreen, settings.channelMixer.green);
lutMaterial.SetVector(Uniforms._ChannelMixerBlue, settings.channelMixer.blue);
// Selective grading & YRGB curves
lutMaterial.SetTexture(Uniforms._Curves, GetCurveTexture());
// Generate the lut
Graphics.Blit(null, model.bakedLut, lutMaterial, 0);
}
public override void Prepare(Material uberMaterial)
{
if (model.isDirty || !IsLogLutValid(model.bakedLut))
{
GenerateLut();
model.isDirty = false;
}
uberMaterial.EnableKeyword(
context.profile.debugViews.IsModeActive(DebugMode.PreGradingLog)
? "COLOR_GRADING_LOG_VIEW"
: "COLOR_GRADING"
);
var bakedLut = model.bakedLut;
uberMaterial.SetTexture(Uniforms._LogLut, bakedLut);
uberMaterial.SetVector(Uniforms._LogLut_Params, new Vector3(1f / bakedLut.width, 1f / bakedLut.height, bakedLut.height - 1f));
float ev = Mathf.Exp(model.settings.basic.postExposure * 0.69314718055994530941723212145818f);
uberMaterial.SetFloat(Uniforms._ExposureEV, ev);
}
public void OnGUI()
{
var bakedLut = model.bakedLut;
var rect = new Rect(context.viewport.x * Screen.width + 8f, 8f, bakedLut.width, bakedLut.height);
GUI.DrawTexture(rect, bakedLut);
}
public override void OnDisable()
{
GraphicsUtils.Destroy(m_GradingCurves);
GraphicsUtils.Destroy(model.bakedLut);
m_GradingCurves = null;
model.bakedLut = null;
}
}
}
| |
//
// 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.Azure.Management.DataFactories;
using Microsoft.Azure.Management.DataFactories.Models;
namespace Microsoft.Azure.Management.DataFactories
{
public static partial class TableOperationsExtensions
{
/// <summary>
/// Create a new table instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a table.
/// </param>
/// <returns>
/// The CreateOrUpdate table operation response.
/// </returns>
public static TableCreateOrUpdateResponse BeginCreateOrUpdate(this ITableOperations operations, string resourceGroupName, string dataFactoryName, TableCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITableOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a new table instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a table.
/// </param>
/// <returns>
/// The CreateOrUpdate table operation response.
/// </returns>
public static Task<TableCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this ITableOperations operations, string resourceGroupName, string dataFactoryName, TableCreateOrUpdateParameters parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None);
}
/// <summary>
/// Create a new table instance or update an existing instance with raw
/// json content.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. A unique table instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a table.
/// </param>
/// <returns>
/// The CreateOrUpdate table operation response.
/// </returns>
public static TableCreateOrUpdateResponse BeginCreateOrUpdateWithRawJsonContent(this ITableOperations operations, string resourceGroupName, string dataFactoryName, string tableName, TableCreateOrUpdateWithRawJsonContentParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITableOperations)s).BeginCreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, tableName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a new table instance or update an existing instance with raw
/// json content.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. A unique table instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a table.
/// </param>
/// <returns>
/// The CreateOrUpdate table operation response.
/// </returns>
public static Task<TableCreateOrUpdateResponse> BeginCreateOrUpdateWithRawJsonContentAsync(this ITableOperations operations, string resourceGroupName, string dataFactoryName, string tableName, TableCreateOrUpdateWithRawJsonContentParameters parameters)
{
return operations.BeginCreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, tableName, parameters, CancellationToken.None);
}
/// <summary>
/// Delete a table instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. Name of the table.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginDelete(this ITableOperations operations, string resourceGroupName, string dataFactoryName, string tableName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITableOperations)s).BeginDeleteAsync(resourceGroupName, dataFactoryName, tableName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a table instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. Name of the table.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginDeleteAsync(this ITableOperations operations, string resourceGroupName, string dataFactoryName, string tableName)
{
return operations.BeginDeleteAsync(resourceGroupName, dataFactoryName, tableName, CancellationToken.None);
}
/// <summary>
/// Create a new table instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a table.
/// </param>
/// <returns>
/// The CreateOrUpdate table operation response.
/// </returns>
public static TableCreateOrUpdateResponse CreateOrUpdate(this ITableOperations operations, string resourceGroupName, string dataFactoryName, TableCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITableOperations)s).CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a new table instance or update an existing instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a table.
/// </param>
/// <returns>
/// The CreateOrUpdate table operation response.
/// </returns>
public static Task<TableCreateOrUpdateResponse> CreateOrUpdateAsync(this ITableOperations operations, string resourceGroupName, string dataFactoryName, TableCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None);
}
/// <summary>
/// Create a new table instance or update an existing instance with raw
/// json content.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. A unique table instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a table.
/// </param>
/// <returns>
/// The CreateOrUpdate table operation response.
/// </returns>
public static TableCreateOrUpdateResponse CreateOrUpdateWithRawJsonContent(this ITableOperations operations, string resourceGroupName, string dataFactoryName, string tableName, TableCreateOrUpdateWithRawJsonContentParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITableOperations)s).CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, tableName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a new table instance or update an existing instance with raw
/// json content.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. A unique table instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a table.
/// </param>
/// <returns>
/// The CreateOrUpdate table operation response.
/// </returns>
public static Task<TableCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(this ITableOperations operations, string resourceGroupName, string dataFactoryName, string tableName, TableCreateOrUpdateWithRawJsonContentParameters parameters)
{
return operations.CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, tableName, parameters, CancellationToken.None);
}
/// <summary>
/// Delete a table instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. Name of the table.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse Delete(this ITableOperations operations, string resourceGroupName, string dataFactoryName, string tableName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITableOperations)s).DeleteAsync(resourceGroupName, dataFactoryName, tableName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a table instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. Name of the table.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> DeleteAsync(this ITableOperations operations, string resourceGroupName, string dataFactoryName, string tableName)
{
return operations.DeleteAsync(resourceGroupName, dataFactoryName, tableName, CancellationToken.None);
}
/// <summary>
/// Gets a table instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. Name of the table.
/// </param>
/// <returns>
/// The Get table operation response.
/// </returns>
public static TableGetResponse Get(this ITableOperations operations, string resourceGroupName, string dataFactoryName, string tableName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITableOperations)s).GetAsync(resourceGroupName, dataFactoryName, tableName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a table instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. Name of the table.
/// </param>
/// <returns>
/// The Get table operation response.
/// </returns>
public static Task<TableGetResponse> GetAsync(this ITableOperations operations, string resourceGroupName, string dataFactoryName, string tableName)
{
return operations.GetAsync(resourceGroupName, dataFactoryName, tableName, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// The CreateOrUpdate table operation response.
/// </returns>
public static TableCreateOrUpdateResponse GetCreateOrUpdateStatus(this ITableOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITableOperations)s).GetCreateOrUpdateStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// The CreateOrUpdate table operation response.
/// </returns>
public static Task<TableCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(this ITableOperations operations, string operationStatusLink)
{
return operations.GetCreateOrUpdateStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Gets all the table instances in a data factory with the link to the
/// next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <returns>
/// The List tables operation response.
/// </returns>
public static TableListResponse List(this ITableOperations operations, string resourceGroupName, string dataFactoryName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITableOperations)s).ListAsync(resourceGroupName, dataFactoryName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the table instances in a data factory with the link to the
/// next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <returns>
/// The List tables operation response.
/// </returns>
public static Task<TableListResponse> ListAsync(this ITableOperations operations, string resourceGroupName, string dataFactoryName)
{
return operations.ListAsync(resourceGroupName, dataFactoryName, CancellationToken.None);
}
/// <summary>
/// Gets the next page of table instances with the link to the next
/// page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to the next tables page.
/// </param>
/// <returns>
/// The List tables operation response.
/// </returns>
public static TableListResponse ListNext(this ITableOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITableOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the next page of table instances with the link to the next
/// page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.ITableOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to the next tables page.
/// </param>
/// <returns>
/// The List tables operation response.
/// </returns>
public static Task<TableListResponse> ListNextAsync(this ITableOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace ISSE.SafetyChecking.DiscreteTimeMarkovChain
{
using System.Collections.Generic;
using AnalysisModel;
using AnalysisModelTraverser;
using Utilities;
/// <summary>
/// After ITransitionModifiers have been applied onto a TransitionCollection, there might be several transitions
/// which only differ in their probability. This is especially the case when EarlyTermination has been applied,
/// because former different states now go into the same Stuttering state.
/// </summary>
internal sealed unsafe class ConsolidateTransitionsModifier : ITransitionModifier
{
public int ExtraBytesInStateVector { get; } = 0;
public int ExtraBytesOffset { get; set; }
public int RelevantStateVectorSize { get; set; }
private readonly List<IndexWithHash> _sortedTransitions = new List<IndexWithHash>();
private readonly SortTransitionByHashComparer _transitionComparer = new SortTransitionByHashComparer();
private TransitionCollection _transitions;
private bool _useHash;
public int UseHashLimit { get; set; } = 16;
/// <summary>
/// Initializes a new instance.
/// </summary>
public ConsolidateTransitionsModifier()
{
}
/// <summary>
/// Optionally modifies the <paramref name="transitions" />, changing any of their values. However, no new transitions can be
/// added; transitions can be removed by setting their <see cref="CandidateTransition.IsValid" /> flag to <c>false</c>.
/// During subsequent traversal steps, only valid transitions and target states reached by at least one valid transition
/// are considered.
/// </summary>
/// <param name="context">The context of the model traversal.</param>
/// <param name="worker">The worker that found the transition.</param>
/// <param name="transitions">The transitions that should be checked.</param>
/// <param name="sourceState">The source state of the transitions.</param>
/// <param name="sourceStateIndex">The unique index of the transition's source state.</param>
/// <param name="isInitial">Indicates whether the transitions are initial transitions not starting in any valid source state.</param>
public void ModifyTransitions(TraversalContext context, Worker worker, TransitionCollection transitions, byte* sourceState, int sourceStateIndex, bool isInitial)
{
_transitions = transitions;
_useHash = transitions.Count >= UseHashLimit;
CreateSortedTransitionIndexes();
IterateThroughAllTransitionsInSortedOrder();
}
private void IterateThroughAllTransitionsInSortedOrder()
{
var mergeInCandidateIndex = 0;
while (mergeInCandidateIndex < _transitions.Count)
{
var mergeInCandidate = GetCandidateTransition(mergeInCandidateIndex);
if (TransitionFlags.IsValid(mergeInCandidate->Flags))
{
MergeCandidateWithAllApplicableTargets(mergeInCandidate, mergeInCandidateIndex);
}
mergeInCandidateIndex++;
}
}
private void MergeCandidateWithAllApplicableTargets(LtmcTransition* mergeInCandidate, int mergeInCandidateIndex)
{
var mergeInCandidateHash = GetCandidateHash(mergeInCandidateIndex);
var toMergeCandidateIndex = mergeInCandidateIndex + 1;
while (!CandidateIsOutOfIndexOrHasDifferentHash(mergeInCandidateHash,toMergeCandidateIndex))
{
var toMergeCandidate = GetCandidateTransition(toMergeCandidateIndex);
if (TransitionFlags.IsValid(toMergeCandidate->Flags))
{
if (CanTransitionsBeMerged(mergeInCandidate, toMergeCandidate))
{
MergeTransitions(mergeInCandidate, toMergeCandidate);
}
}
toMergeCandidateIndex++;
}
}
private bool CandidateIsOutOfIndexOrHasDifferentHash(uint mergeInCandidateHash, int toMergeCandidateIndex)
{
if (toMergeCandidateIndex >= _transitions.Count)
{
return true;
}
var toMergeCandidateHash = GetCandidateHash(toMergeCandidateIndex);
return mergeInCandidateHash != toMergeCandidateHash;
}
private LtmcTransition* GetCandidateTransition(int sortedIndex)
{
var indexInTransitions = _sortedTransitions[sortedIndex].Index;
return (LtmcTransition*)_transitions[indexInTransitions];
}
private uint GetCandidateHash(int sortedIndex)
{
if (!_useHash)
return 0;
return _sortedTransitions[sortedIndex].Hash;
}
private uint HashTransition(LtmcTransition* transition)
{
// hashing see FNV hash at http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
if (!TransitionFlags.IsValid(transition->Flags))
{
return 0;
}
unchecked
{
uint hash = 0;
if (!TransitionFlags.IsToStutteringState(transition->Flags))
hash = MemoryBuffer.Hash(transition->TargetStatePointer, RelevantStateVectorSize, 0);
hash = hash * 397 ^ (uint)transition->Formulas.GetHashCode();
return hash;
}
}
public void CreateSortedTransitionIndexes()
{
_sortedTransitions.Clear();
for (var i = 0; i < _transitions.Count; i++)
{
var newSortedTransition = new IndexWithHash();
newSortedTransition.Index = i;
var transition = (LtmcTransition*)_transitions[i];
newSortedTransition.Hash = HashTransition(transition);
_sortedTransitions.Add(newSortedTransition);
}
if (_useHash)
{
_sortedTransitions.Sort(_transitionComparer);
}
}
private bool CanTransitionsBeMerged(LtmcTransition* a, LtmcTransition* b)
{
var aToStuttering = TransitionFlags.IsToStutteringState(a->Flags);
var bToStuttering = TransitionFlags.IsToStutteringState(b->Flags);
if (aToStuttering != bToStuttering)
{
// Target states do not match
return false;
}
if (!aToStuttering)
{
// both target states are not the stuttering state. So check if the states match
if (!MemoryBuffer.AreEqual(a->TargetStatePointer, b->TargetStatePointer, RelevantStateVectorSize))
return false;
}
if (a->Flags != b->Flags)
return false;
if (a->Formulas != b->Formulas)
return false;
return true;
}
private void MergeTransitions(LtmcTransition* mergeInCandidate, LtmcTransition* toMergeCandidate)
{
mergeInCandidate->Probability += toMergeCandidate->Probability;
toMergeCandidate->Flags = TransitionFlags.RemoveValid(toMergeCandidate->Flags);
}
private struct IndexWithHash
{
public long Index;
public uint Hash;
}
private class SortTransitionByHashComparer : IComparer<IndexWithHash>
{
public int Compare(IndexWithHash x, IndexWithHash y)
{
return x.Hash.CompareTo(y.Hash);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void RoundToNegativeInfinitySingle()
{
var test = new SimpleUnaryOpTest__RoundToNegativeInfinitySingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__RoundToNegativeInfinitySingle
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Single);
private const int RetElementCount = VectorSize / sizeof(Single);
private static Single[] _data = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar;
private Vector128<Single> _fld;
private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable;
static SimpleUnaryOpTest__RoundToNegativeInfinitySingle()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__RoundToNegativeInfinitySingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.RoundToNegativeInfinity(
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.RoundToNegativeInfinity(
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.RoundToNegativeInfinity(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNegativeInfinity), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNegativeInfinity), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNegativeInfinity), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.RoundToNegativeInfinity(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr);
var result = Sse41.RoundToNegativeInfinity(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse.LoadVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse41.RoundToNegativeInfinity(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse41.RoundToNegativeInfinity(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__RoundToNegativeInfinitySingle();
var result = Sse41.RoundToNegativeInfinity(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.RoundToNegativeInfinity(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Floor(firstOp[0])))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(MathF.Floor(firstOp[i])))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.RoundToNegativeInfinity)}<Single>(Vector128<Single>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
namespace Orleans
{
namespace Concurrency
{
/// <summary>
/// The ReadOnly attribute is used to mark methods that do not modify the state of a grain.
/// <para>
/// Marking methods as ReadOnly allows the run-time system to perform a number of optimizations
/// that may significantly improve the performance of your application.
/// </para>
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
internal sealed class ReadOnlyAttribute : Attribute
{
}
/// <summary>
/// The Reentrant attribute is used to mark grain implementation classes that allow request interleaving within a task.
/// <para>
/// This is an advanced feature and should not be used unless the implications are fully understood.
/// That said, allowing request interleaving allows the run-time system to perform a number of optimizations
/// that may significantly improve the performance of your application.
/// </para>
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class ReentrantAttribute : Attribute
{
}
/// <summary>
/// The Unordered attribute is used to mark grain interface in which the delivery order of
/// messages is not significant.
/// </summary>
[AttributeUsage(AttributeTargets.Interface)]
public sealed class UnorderedAttribute : Attribute
{
}
/// <summary>
/// The StatelessWorker attribute is used to mark grain class in which there is no expectation
/// of preservation of grain state between requests and where multiple activations of the same grain are allowed to be created by the runtime.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class StatelessWorkerAttribute : Attribute
{
/// <summary>
/// Maximal number of local StatelessWorkers in a single silo.
/// </summary>
public int MaxLocalWorkers { get; private set; }
public StatelessWorkerAttribute(int maxLocalWorkers)
{
MaxLocalWorkers = maxLocalWorkers;
}
public StatelessWorkerAttribute()
{
MaxLocalWorkers = -1;
}
}
/// <summary>
/// The AlwaysInterleaveAttribute attribute is used to mark methods that can interleave with any other method type, including write (non ReadOnly) requests.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
public sealed class AlwaysInterleaveAttribute : Attribute
{
}
/// <summary>
/// The Immutable attribute indicates that instances of the marked class or struct are never modified
/// after they are created.
/// </summary>
/// <remarks>
/// Note that this implies that sub-objects are also not modified after the instance is created.
/// </remarks>
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class)]
public sealed class ImmutableAttribute : Attribute
{
}
}
namespace Placement
{
using Orleans.Runtime;
/// <summary>
/// Base for all placement policy marker attributes.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public abstract class PlacementAttribute : Attribute
{
internal PlacementStrategy PlacementStrategy { get; private set; }
internal PlacementAttribute(PlacementStrategy placement)
{
PlacementStrategy = placement ?? PlacementStrategy.GetDefault();
}
}
/// <summary>
/// Marks a grain class as using the <c>RandomPlacement</c> policy.
/// </summary>
/// <remarks>
/// This is the default placement policy, so this attribute does not need to be used for normal grains.
/// </remarks>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public sealed class RandomPlacementAttribute : PlacementAttribute
{
public RandomPlacementAttribute() :
base(RandomPlacement.Singleton)
{ }
}
/// <summary>
/// Marks a grain class as using the <c>PreferLocalPlacement</c> policy.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false) ]
public sealed class PreferLocalPlacementAttribute : PlacementAttribute
{
public PreferLocalPlacementAttribute() :
base(PreferLocalPlacement.Singleton)
{ }
}
/// <summary>
/// Marks a grain class as using the <c>ActivationCountBasedPlacement</c> policy.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public sealed class ActivationCountBasedPlacementAttribute : PlacementAttribute
{
public ActivationCountBasedPlacementAttribute() :
base(ActivationCountBasedPlacement.Singleton)
{ }
}
}
namespace CodeGeneration
{
/// <summary>
/// The TypeCodeOverrideAttribute attribute allows to specify the grain interface ID or the grain class type code
/// to override the default ones to avoid hash collisions
/// </summary>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class)]
public sealed class TypeCodeOverrideAttribute : Attribute
{
/// <summary>
/// Use a specific grain interface ID or grain class type code (e.g. to avoid hash collisions)
/// </summary>
public int TypeCode { get; private set; }
public TypeCodeOverrideAttribute(int typeCode)
{
TypeCode = typeCode;
}
}
/// <summary>
/// Used to mark a method as providing a copier function for that type.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class CopierMethodAttribute : Attribute
{
}
/// <summary>
/// Used to mark a method as providinga serializer function for that type.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SerializerMethodAttribute : Attribute
{
}
/// <summary>
/// Used to mark a method as providing a deserializer function for that type.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class DeserializerMethodAttribute : Attribute
{
}
/// <summary>
/// Used to make a class for auto-registration as a serialization helper.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class RegisterSerializerAttribute : Attribute
{
}
}
namespace Providers
{
/// <summary>
/// The [Orleans.Providers.StorageProvider] attribute is used to define which storage provider to use for persistence of grain state.
/// <para>
/// Specifying [Orleans.Providers.StorageProvider] property is recommended for all grains which extend Grain<T>.
/// If no [Orleans.Providers.StorageProvider] attribute is specified, then a "Default" strorage provider will be used.
/// If a suitable storage provider cannot be located for this grain, then the grain will fail to load into the Silo.
/// </para>
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class StorageProviderAttribute : Attribute
{
public StorageProviderAttribute()
{
ProviderName = Runtime.Constants.DEFAULT_STORAGE_PROVIDER_NAME;
}
/// <summary>
/// The name of the storage provider to ne used for persisting state for this grain.
/// </summary>
public string ProviderName { get; set; }
}
}
[AttributeUsage(AttributeTargets.Interface)]
internal sealed class FactoryAttribute : Attribute
{
public enum FactoryTypes
{
Grain,
ClientObject,
Both
};
private readonly FactoryTypes factoryType = FactoryTypes.Grain;
public FactoryAttribute(FactoryTypes factoryType)
{
this.factoryType = factoryType;
}
internal static FactoryTypes CollectFactoryTypesSpecified(Type type)
{
var attribs = type.GetCustomAttributes(typeof(FactoryAttribute), inherit: true);
// if no attributes are specified, we default to FactoryTypes.Grain.
if (0 == attribs.Length)
return FactoryTypes.Grain;
// otherwise, we'll consider all of them and aggregate the specifications
// like flags.
FactoryTypes? result = null;
foreach (var i in attribs)
{
var a = (FactoryAttribute)i;
if (result.HasValue)
{
if (a.factoryType == FactoryTypes.Both)
result = a.factoryType;
else if (a.factoryType != result.Value)
result = FactoryTypes.Both;
}
else
result = a.factoryType;
}
if (result.Value == FactoryTypes.Both)
{
throw
new NotSupportedException(
"Orleans doesn't currently support generating both a grain and a client object factory but we really want to!");
}
return result.Value;
}
public static FactoryTypes CollectFactoryTypesSpecified<T>()
{
return CollectFactoryTypesSpecified(typeof(T));
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple=true)]
public sealed class ImplicitStreamSubscriptionAttribute : Attribute
{
internal string Namespace { get; private set; }
// We have not yet come to an agreement whether the provider should be specified as well.
public ImplicitStreamSubscriptionAttribute(string streamNamespace)
{
Namespace = streamNamespace;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
namespace FluentLogger
{
/// <summary>
/// A fluent <see langword="interface"/> to build log messages.
/// </summary>
public sealed class LogBuilder : ILogBuilder
{
private readonly LogData _data;
private readonly ILogWriter _writer;
private readonly IObjectPool<LogBuilder> _objectPool;
/// <summary>
/// Initializes a new instance of the <see cref="LogBuilder" /> class.
/// </summary>
/// <param name="writer">The delegate to write logs to.</param>
/// <param name="objectPool">The object pool.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="writer" /> is <see langword="null" />.</exception>
internal LogBuilder(ILogWriter writer, IObjectPool<LogBuilder> objectPool)
: this(writer)
{
_objectPool = objectPool;
}
/// <summary>
/// Initializes a new instance of the <see cref="LogBuilder" /> class.
/// </summary>
/// <param name="writer">The delegate to write logs to.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="writer" /> is <see langword="null" />.</exception>
public LogBuilder(ILogWriter writer)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer));
_writer = writer;
_data = new LogData();
}
/// <summary>
/// Gets the log data that is being built.
/// </summary>
/// <value>
/// The log data.
/// </value>
public LogData LogData
{
get { return _data; }
}
/// <summary>
/// Sets the level of the logging event.
/// </summary>
/// <param name="logLevel">The level of the logging event.</param>
/// <returns></returns>
public ILogBuilder Level(LogLevel logLevel)
{
_data.LogLevel = logLevel;
return this;
}
/// <summary>
/// Sets the logger for the logging event.
/// </summary>
/// <param name="logger">The name of the logger.</param>
/// <returns></returns>
public ILogBuilder Logger(string logger)
{
_data.Logger = logger;
return this;
}
/// <summary>
/// Sets the logger name using the generic type.
/// </summary>
/// <typeparam name="TLogger">The type of the logger.</typeparam>
/// <returns></returns>
public ILogBuilder Logger<TLogger>()
{
_data.Logger = typeof(TLogger).FullName;
return this;
}
/// <summary>
/// Sets the log message on the logging event.
/// </summary>
/// <param name="message">The log message for the logging event.</param>
/// <returns></returns>
public ILogBuilder Message(string message)
{
_data.Message = message;
return this;
}
/// <summary>
/// Sets the log message on the logging event using the return value of specified <see langword="delegate" />.
/// </summary>
/// <param name="messageFactory">The <see langword="delegate" /> to generate the method.</param>
/// <returns></returns>
public ILogBuilder Message(Func<string> messageFactory)
{
_data.MessageFormatter = messageFactory;
return this;
}
/// <summary>
/// Sets the log message and parameters for formating on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The object to format.</param>
/// <returns></returns>
public ILogBuilder Message(string format, object arg0)
{
_data.Message = format;
_data.Parameters = new[] { arg0 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formating on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <returns></returns>
public ILogBuilder Message(string format, object arg0, object arg1)
{
_data.Message = format;
_data.Parameters = new[] { arg0, arg1 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formating on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <param name="arg2">The third object to format.</param>
/// <returns></returns>
public ILogBuilder Message(string format, object arg0, object arg1, object arg2)
{
_data.Message = format;
_data.Parameters = new[] { arg0, arg1, arg2 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formating on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <param name="arg2">The third object to format.</param>
/// <param name="arg3">The fourth object to format.</param>
/// <returns></returns>
public ILogBuilder Message(string format, object arg0, object arg1, object arg2, object arg3)
{
_data.Message = format;
_data.Parameters = new[] { arg0, arg1, arg2, arg3 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formating on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns></returns>
public ILogBuilder Message(string format, params object[] args)
{
_data.Message = format;
_data.Parameters = args;
return this;
}
/// <summary>
/// Sets the log message and parameters for formating on the logging event.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns></returns>
public ILogBuilder Message(IFormatProvider provider, string format, params object[] args)
{
_data.FormatProvider = provider;
_data.Message = format;
_data.Parameters = args;
return this;
}
/// <summary>
/// Sets a log context property on the logging event.
/// </summary>
/// <param name="name">The name of the context property.</param>
/// <param name="value">The value of the context property.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">name</exception>
public ILogBuilder Property(string name, object value)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (_data.Properties == null)
_data.Properties = new Dictionary<string, object>();
_data.Properties[name] = value;
return this;
}
/// <summary>
/// Sets the exception information of the logging event.
/// </summary>
/// <param name="exception">The exception information of the logging event.</param>
/// <returns></returns>
public ILogBuilder Exception(Exception exception)
{
_data.Exception = exception;
return this;
}
/// <summary>
/// Reset log data to default values.
/// </summary>
/// <returns></returns>
internal ILogBuilder Reset()
{
_data.Reset();
return this;
}
/// <summary>
/// Writes the log event to the underlying logger.
/// </summary>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
public void Write(
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (callerMemberName != null)
_data.MemberName = callerMemberName;
if (callerFilePath != null)
_data.FilePath = callerFilePath;
if (callerLineNumber != 0)
_data.LineNumber = callerLineNumber;
_writer.WriteLog(_data);
// return to object pool
_objectPool?.Free(this);
}
/// <summary>
/// Writes the log event to the underlying logger if the condition delegate is true.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
public void WriteIf(
Func<bool> condition,
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (condition == null || !condition())
return;
Write(callerMemberName, callerFilePath, callerLineNumber);
}
/// <summary>
/// Writes the log event to the underlying logger if the condition is true.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
public void WriteIf(
bool condition,
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (!condition)
return;
Write(callerMemberName, callerFilePath, callerLineNumber);
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SafetySharp.Runtime.Serialization
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Utilities;
using ISSE.SafetyChecking.Utilities;
/// <summary>
/// Describes the contents stored in a state slot of a state vector.
/// </summary>
[Serializable]
public class StateSlotMetadata : IEquatable<StateSlotMetadata>
{
/// <summary>
/// The compressed type of the data stored in the slot.
/// </summary>
public Type CompressedDataType;
/// <summary>
/// The uncompressed type of the data stored in the slot.
/// </summary>
public Type DataType;
/// <summary>
/// The number of elements the data consists of.
/// </summary>
public int ElementCount;
/// <summary>
/// The field stored in the slot, if any.
/// </summary>
public FieldInfo Field;
/// <summary>
/// The chain of fields if the data is stored in possibly nested structs.
/// </summary>
public FieldInfo[] FieldChain;
/// <summary>
/// The object whose data is stored in the slot.
/// </summary>
[NonSerialized]
public object Object;
/// <summary>
/// The identifier of the object whose data is stored in the slot.
/// </summary>
public int ObjectIdentifier;
/// <summary>
/// The type of the object whose data is stored in the slot.
/// </summary>
public Type ObjectType;
/// <summary>
/// The range metadata of the slot, if any.
/// </summary>
[NonSerialized]
public RangeMetadata Range;
/// <summary>
/// Gets a value indicating whether the data is stored in a struct.
/// </summary>
public bool ContainedInStruct => (FieldChain?.Length ?? 0) != 0;
/// <summary>
/// Gets the effective type of the data stored in the slot.
/// </summary>
public Type EffectiveType => CompressedDataType ?? DataType;
/// <summary>
/// Gets the total size in bits required to store the data in the state vector.
/// </summary>
public int TotalSizeInBits => ElementSizeInBits * ElementCount;
/// <summary>
/// Gets the size in bits required to store each individual element in the state vector.
/// </summary>
public int ElementSizeInBits
{
get
{
if (DataType.IsReferenceType())
return sizeof(ushort) * 8;
if (DataType == typeof(bool))
return 1;
return EffectiveType.GetUnmanagedSize() * 8;
}
}
/// <summary>
/// Indicates whether the current object is equal to <paramref name="other" />.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(StateSlotMetadata other)
{
return ObjectIdentifier == other.ObjectIdentifier &&
ObjectType == other.ObjectType &&
ElementCount == other.ElementCount &&
Equals(Field, other.Field) &&
DataType == other.DataType &&
CompressedDataType == other.CompressedDataType &&
(FieldChain?.SequenceEqual(other.FieldChain) ?? true);
}
/// <summary>
/// Indicates whether this instance and <paramref name="obj" /> are equal.
/// </summary>
/// <param name="obj">The object to compare with the current instance.</param>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is StateSlotMetadata && Equals((StateSlotMetadata)obj);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
public override int GetHashCode()
{
throw new NotSupportedException();
}
/// <summary>
/// Checks whether <paramref name="left" /> and <paramref name="right" /> are equal.
/// </summary>
/// <param name="left">The first instance that should be compared.</param>
/// <param name="right">The second instance that should be compared.</param>
public static bool operator ==(StateSlotMetadata left, StateSlotMetadata right)
{
return left?.Equals(right) ?? right == null;
}
/// <summary>
/// Checks whether <paramref name="left" /> and <paramref name="right" /> are not equal.
/// </summary>
/// <param name="left">The first instance that should be compared.</param>
/// <param name="right">The second instance that should be compared.</param>
public static bool operator !=(StateSlotMetadata left, StateSlotMetadata right)
{
return !(left == right);
}
/// <summary>
/// Creates the metadata required to serialize the <paramref name="structType" />.
/// </summary>
/// <param name="structType">The type of the struct the metadata should be created for.</param>
/// <param name="mode">The serialization mode that should be used to serialize the objects.</param>
public static IEnumerable<StateSlotMetadata> FromStruct(Type structType, SerializationMode mode)
{
Requires.NotNull(structType, nameof(structType));
Requires.That(structType.IsStructType(), "Expected a value type.");
return FromStruct(structType, mode, new FieldInfo[0]);
}
/// <summary>
/// Creates the metadata required to serialize the <paramref name="structType" /> with the <paramref name="fieldChain" />.
/// </summary>
private static IEnumerable<StateSlotMetadata> FromStruct(Type structType, SerializationMode mode, FieldInfo[] fieldChain)
{
foreach (var field in SerializationRegistry.GetSerializationFields(structType, mode))
{
var chain = fieldChain.Concat(new[] { field }).ToArray();
if (field.FieldType.IsStructType())
{
foreach (var metadataSlot in FromStruct(field.FieldType, mode, chain))
yield return metadataSlot;
}
else
{
yield return new StateSlotMetadata
{
DataType = field.FieldType,
FieldChain = chain
};
}
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Util;
using QuantConnect.Interfaces;
// ReSharper disable InvokeAsExtensionMethod -- .net 4.7.2 added ToHashSet and it looks like our version of mono has it as well causing ambiguity in the cloud
namespace QuantConnect.Algorithm.CSharp
{
public class AddRemoveOptionUniverseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "GOOG";
public readonly Symbol Underlying = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Equity, Market.USA);
public readonly Symbol OptionChainSymbol = QuantConnect.Symbol.Create(UnderlyingTicker, SecurityType.Option, Market.USA);
private readonly HashSet<Symbol> _expectedSecurities = new HashSet<Symbol>();
private readonly HashSet<Symbol> _expectedData = new HashSet<Symbol>();
private readonly HashSet<Symbol> _expectedUniverses = new HashSet<Symbol>();
// order of expected contract additions as price moves
private int _expectedContractIndex;
private readonly List<Symbol> _expectedContracts = new List<Symbol>
{
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00747500"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00750000"),
SymbolRepresentation.ParseOptionTickerOSI("GOOG 151224P00752500")
};
public override void Initialize()
{
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 24);
var goog = AddEquity(UnderlyingTicker);
// expect GOOG equity
_expectedData.Add(goog.Symbol);
_expectedSecurities.Add(goog.Symbol);
// expect user defined universe holding GOOG equity
_expectedUniverses.Add(UserDefinedUniverse.CreateSymbol(SecurityType.Equity, Market.USA));
}
public override void OnData(Slice data)
{
// verify expectations
if (!data.ContainsKey(Underlying))
{
// TODO : In fact, we're unable to properly detect whether or not we auto-added or it was manually added
// this is because when we auto-add the underlying we don't mark it as an internal security like we do with other auto adds
// so there's currently no good way to remove the underlying equity without invoking RemoveSecurity(underlying) manually
// from the algorithm, otherwise we may remove it incorrectly. Now, we could track MORE state, but it would likely be a duplication
// of the internal flag's purpose, so kicking this issue for now with a big fat note here about it :) to be considerd for any future
// refactorings of how we manage subscription/security data and track various aspects about the security (thinking a flags enum with
// things like manually added, auto added, internal, and any other boolean state we need to track against a single security)
throw new Exception("The underlying equity data should NEVER be removed in this algorithm because it was manually added");
}
if (_expectedSecurities.AreDifferent(LinqExtensions.ToHashSet(Securities.Keys)))
{
var expected = string.Join(Environment.NewLine, _expectedSecurities.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, Securities.Keys.OrderBy(s => s.ToString()));
throw new Exception($"{Time}:: Detected differences in expected and actual securities{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
}
if (_expectedUniverses.AreDifferent(LinqExtensions.ToHashSet(UniverseManager.Keys)))
{
var expected = string.Join(Environment.NewLine, _expectedUniverses.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, UniverseManager.Keys.OrderBy(s => s.ToString()));
throw new Exception($"{Time}:: Detected differences in expected and actual universes{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
}
if (_expectedData.AreDifferent(LinqExtensions.ToHashSet(data.Keys)))
{
var expected = string.Join(Environment.NewLine, _expectedData.OrderBy(s => s.ToString()));
var actual = string.Join(Environment.NewLine, data.Keys.OrderBy(s => s.ToString()));
throw new Exception($"{Time}:: Detected differences in expected and actual slice data keys{Environment.NewLine}Expected:{Environment.NewLine}{expected}{Environment.NewLine}Actual:{Environment.NewLine}{actual}");
}
// 10AM add GOOG option chain
if (Time.TimeOfDay.Hours == 10 && Time.TimeOfDay.Minutes == 0)
{
if (Securities.ContainsKey(OptionChainSymbol))
{
throw new Exception("The option chain security should not have been added yet");
}
var googOptionChain = AddOption(UnderlyingTicker);
googOptionChain.SetFilter(u =>
{
// find first put above market price
return u.IncludeWeeklys()
.Strikes(+1, +1)
.Expiration(TimeSpan.Zero, TimeSpan.FromDays(1))
.Contracts(c => c.Where(s => s.ID.OptionRight == OptionRight.Put));
});
_expectedSecurities.Add(OptionChainSymbol);
_expectedUniverses.Add(OptionChainSymbol);
}
// 11:30AM remove GOOG option chain
if (Time.TimeOfDay.Hours == 11 && Time.TimeOfDay.Minutes == 30)
{
RemoveSecurity(OptionChainSymbol);
// remove contracts from expected data
_expectedData.RemoveWhere(s => _expectedContracts.Contains(s));
// remove option chain universe from expected universes
_expectedUniverses.Remove(OptionChainSymbol);
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
if (changes.AddedSecurities.Count > 1)
{
// added event fired for underlying since it was added to the option chain universe
if (changes.AddedSecurities.All(s => s.Symbol != Underlying))
{
var securities = string.Join(Environment.NewLine, changes.AddedSecurities.Select(s => s.Symbol));
throw new Exception($"This algorithm intends to add a single security at a time but added: {changes.AddedSecurities.Count}{Environment.NewLine}{securities}");
}
}
if (changes.AddedSecurities.Any())
{
foreach (var added in changes.AddedSecurities)
{
// any option security additions for this algorithm should match the expected contracts
if (added.Symbol.SecurityType == SecurityType.Option)
{
var expectedContract = _expectedContracts[_expectedContractIndex];
if (added.Symbol != expectedContract)
{
throw new Exception($"Expected option contract {expectedContract} to be added but received {added.Symbol}");
}
_expectedContractIndex++;
// purchase for regression statistics
MarketOrder(added.Symbol, 1);
}
_expectedData.Add(added.Symbol);
_expectedSecurities.Add(added.Symbol);
}
}
// security removal happens exactly once in this algorithm when the option chain is removed
// and all child subscriptions (option contracts) should be removed at the same time
if (changes.RemovedSecurities.Any(x => x.Symbol.SecurityType == SecurityType.Option))
{
// receive removed event next timestep at 11:31AM
if (Time.TimeOfDay.Hours != 11 || Time.TimeOfDay.Minutes != 31)
{
throw new Exception($"Expected option contracts to be removed at 11:31AM, instead removed at: {Time}");
}
if (changes.RemovedSecurities
.Where(x => x.Symbol.SecurityType == SecurityType.Option)
.ToHashSet(s => s.Symbol)
.AreDifferent(LinqExtensions.ToHashSet(_expectedContracts)))
{
throw new Exception("Expected removed securities to equal expected contracts added");
}
}
if (Securities.ContainsKey(Underlying))
{
Console.WriteLine($"{Time:o}:: PRICE:: {Securities[Underlying].Price} CHANGES:: {changes}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "6"},
{"Average Win", "0%"},
{"Average Loss", "-0.21%"},
{"Compounding Annual Return", "-96.657%"},
{"Drawdown", "0.600%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.626%"},
{"Sharpe Ratio", "0"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.50"}
};
}
}
| |
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 TinderChallenge.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Cdn.Fluent
{
using CdnEndpoint.UpdatePremiumEndpoint;
using CdnEndpoint.UpdateStandardEndpoint;
using CdnProfile.Update;
using ResourceManager.Fluent.Core;
using Models;
using ResourceManager.Fluent;
using ResourceManager.Fluent.Core.ChildResourceActions;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Implementation for CdnEndpoint.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNkbi5pbXBsZW1lbnRhdGlvbi5DZG5FbmRwb2ludEltcGw=
internal partial class CdnEndpointImpl :
ExternalChildResource<ICdnEndpoint, EndpointInner, ICdnProfile, CdnProfileImpl>,
ICdnEndpoint,
CdnEndpoint.Definition.Blank.StandardEndpoint.IStandardEndpoint<CdnProfile.Definition.IWithStandardCreate>,
CdnEndpoint.Definition.Blank.PremiumEndpoint.IPremiumEndpoint<CdnProfile.Definition.IWithPremiumVerizonCreate>,
CdnEndpoint.Definition.IWithStandardAttach<CdnProfile.Definition.IWithStandardCreate>,
CdnEndpoint.Definition.IWithPremiumAttach<CdnProfile.Definition.IWithPremiumVerizonCreate>,
CdnEndpoint.UpdateDefinition.Blank.StandardEndpoint.IStandardEndpoint<CdnProfile.Update.IUpdate>,
CdnEndpoint.UpdateDefinition.Blank.PremiumEndpoint.IPremiumEndpoint<CdnProfile.Update.IUpdate>,
CdnEndpoint.UpdateDefinition.IWithStandardAttach<CdnProfile.Update.IUpdate>,
CdnEndpoint.UpdateDefinition.IWithPremiumAttach<CdnProfile.Update.IUpdate>,
IUpdateStandardEndpoint,
IUpdatePremiumEndpoint
{
private List<CustomDomainInner> customDomainList;
private List<CustomDomainInner> deletedCustomDomainList;
string IExternalChildResource<ICdnEndpoint, ICdnProfile>.Id
{
get
{
return Inner.Id;
}
}
///GENMHASH:AD2E24D9DFB738D4BF1A5F65CE996552:03764A67ECF90331193C59D0D3F1DA4D
public CustomDomainValidationResult ValidateCustomDomain(string hostName)
{
return Extensions.Synchronize(() => ValidateCustomDomainAsync(hostName));
}
///GENMHASH:0F38250A3837DF9C2C345D4A038B654B:A5F7C81073BA64AE03AC5C595EE8B6E5
public void Start()
{
Extensions.Synchronize(() => Parent.StartEndpointAsync(Name()));
}
///GENMHASH:EB854F18026EDB6E01762FA4580BE789:5A2F4445DA73DB06DF8066E5B2B6EF28
public void Stop()
{
Extensions.Synchronize(() => StopAsync());
}
///GENMHASH:1B8CF897C7FAD58F437E8F871BCBB60A:E1BA036C25473C6E724281B08EBBF98F
public void LoadContent(ISet<string> contentPaths)
{
Extensions.Synchronize(() => LoadContentAsync(contentPaths));
}
///GENMHASH:5DF0B3F994DC5D52A24BD724F4ED7028:433357741C745D4512DE012A88EDD0AE
public void PurgeContent(ISet<string> contentPaths)
{
if (contentPaths != null)
{
Extensions.Synchronize(() => PurgeContentAsync(contentPaths));
}
}
///GENMHASH:5E567D525C2D1A4E96F5EDCE712176A4:E661050B2228F0D19D27F5E798A9AAED
internal CdnEndpointImpl WithOrigin(string originName, string hostname)
{
Inner.Origins.Add(
new DeepCreatedOrigin
{
Name = originName,
HostName = hostname
});
return this;
}
///GENMHASH:21CB0BD3DBCE4F803F8717FE67D484A9:5C329AC5714B2CF2EDE8689B96916F37
public CdnEndpointImpl WithOrigin(string hostname)
{
return this.WithOrigin("origin", hostname);
}
///GENMHASH:18D91A64C4BA864D24E2DE4DD2523297:08F121BA4E95C8CA8A60DE2B6D8A259A
public CdnEndpointImpl WithQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior)
{
Inner.QueryStringCachingBehavior = cachingBehavior;
return this;
}
///GENMHASH:BA650B492EF1E2A3A4C8226C4A669B7F:3DDBCC9A4C358BBA941924D7644F0538
public CdnEndpointImpl WithHttpsPort(int httpsPort)
{
if (Inner.Origins != null && Inner.Origins.Any())
{
Inner.Origins.ElementAt(0).HttpsPort = httpsPort;
}
return this;
}
///GENMHASH:32A8B56FE180FA4429482D706189DEA2:E688E3B95BC05DCDA88564DDB6B8C0A2
public async override Task<Microsoft.Azure.Management.Cdn.Fluent.ICdnEndpoint> CreateAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var endpointInner = await Parent.Manager.Inner.Endpoints.CreateAsync(
Parent.ResourceGroupName,
Parent.Name,
Name(),
Inner,
cancellationToken);
SetInner(endpointInner);
foreach (var itemToCreate in this.customDomainList)
{
await Parent.Manager.Inner.CustomDomains.CreateAsync(
Parent.ResourceGroupName,
Parent.Name,
Name(),
SdkContext.RandomResourceName("CustomDomain", 50),
itemToCreate.HostName,
cancellationToken);
}
customDomainList.Clear();
customDomainList.AddRange(
await Parent.Manager.Inner.CustomDomains.ListByEndpointAsync(
Parent.ResourceGroupName,
Parent.Name,
Name(),
cancellationToken));
return this;
}
///GENMHASH:F106CA48042B7BF747ACE119F4CFD85D:E96AF02A816CBDFCC8360643D930578E
public async Task PurgeContentAsync(ISet<string> contentPaths, CancellationToken cancellationToken = default(CancellationToken))
{
await this.Parent.PurgeEndpointContentAsync(this.Name(), contentPaths, cancellationToken);
}
///GENMHASH:D5D59EB5CA82A8AB794662C7BE5DC553:B3CB07BBD45377B8277115EC46260752
public CdnEndpointImpl WithPremiumOrigin(string originName, string hostname)
{
return this.WithOrigin(originName, hostname);
}
///GENMHASH:F71E48F5B3D69E8C24335B207B0C3D6D:5CA83E956D3104EE4C9ADD7A88955055
public CdnEndpointImpl WithPremiumOrigin(string hostname)
{
return this.WithOrigin(hostname);
}
///GENMHASH:6896CCD591C3EF6769DA6EA9BB2D4A18:D8F827C6145C2C2B5C33E77ACD483F16
public async Task LoadContentAsync(ISet<string> contentPaths, CancellationToken cancellationToken = default(CancellationToken))
{
await this.Parent.LoadEndpointContentAsync(this.Name(), contentPaths, cancellationToken);
}
///GENMHASH:F08598A17ADD014E223DFD77272641FF:F733ABC4C4375BDE663CF05B96352BF2
public async override Task<Microsoft.Azure.Management.Cdn.Fluent.ICdnEndpoint> UpdateAsync(CancellationToken cancellationToken = default(CancellationToken))
{
EndpointUpdateParametersInner updateInner = new EndpointUpdateParametersInner
{
IsHttpAllowed = Inner.IsHttpAllowed,
IsHttpsAllowed = Inner.IsHttpsAllowed,
OriginPath = Inner.OriginPath,
OriginHostHeader = Inner.OriginHostHeader,
IsCompressionEnabled = Inner.IsCompressionEnabled,
ContentTypesToCompress = Inner.ContentTypesToCompress,
GeoFilters = Inner.GeoFilters,
OptimizationType = Inner.OptimizationType,
QueryStringCachingBehavior = Inner.QueryStringCachingBehavior,
Tags = Inner.Tags
};
DeepCreatedOrigin originInner = Inner.Origins.ElementAt(0);
OriginUpdateParametersInner originParameters = new OriginUpdateParametersInner
{
HostName = originInner.HostName,
HttpPort = originInner.HttpPort,
HttpsPort = originInner.HttpsPort
};
await Task.WhenAll(deletedCustomDomainList
.Select(itemToDelete => Parent.Manager.Inner.CustomDomains.DeleteAsync(
Parent.ResourceGroupName,
Parent.Name,
Name(),
itemToDelete.Name,
cancellationToken)));
deletedCustomDomainList.Clear();
await Parent.Manager.Inner.Origins.UpdateAsync(
Parent.ResourceGroupName,
Parent.Name,
Name(),
originInner.Name,
originParameters,
cancellationToken);
var endpointInner = await Parent.Manager.Inner.Endpoints.UpdateAsync(
Parent.ResourceGroupName,
Parent.Name,
Name(),
updateInner,
cancellationToken);
SetInner(endpointInner);
return this;
}
///GENMHASH:DEAE39A7D24B41C1AF6ABFA406FD058B:997BF86B1AE48764E97C384BDB52387E
public string ResourceState()
{
return Inner.ResourceState;
}
///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:899F2B088BBBD76CCBC31221756265BC
public string Id()
{
return Inner.Id;
}
///GENMHASH:50951E75802920DF638B9F82BEC67147:0486B1BC9AE097182CCECA801B4C0A3C
public CdnEndpointImpl WithContentTypeToCompress(string contentTypeToCompress)
{
if (Inner.ContentTypesToCompress == null)
{
Inner.ContentTypesToCompress = new List<string>();
}
Inner.ContentTypesToCompress.Add(contentTypeToCompress);
return this;
}
///GENMHASH:3BC1B56E1EA6D8692923934DD96FA69E:3E899646D6EF65C7F18D49308FB9672A
public IReadOnlyList<Microsoft.Azure.Management.Cdn.Fluent.Models.GeoFilter> GeoFilters()
{
return Inner.GeoFilters?.ToList();
}
///GENMHASH:6F62B34CB3A912AA692DBF18C6F448CB:A04B2C5688B47A48AC0B72C698E4AFC4
public CdnEndpointImpl WithHostHeader(string hostHeader)
{
Inner.OriginHostHeader = hostHeader;
return this;
}
///GENMHASH:52A2DCF36C3A58BEC0D85E7C013DD0A4:4E93ADCD1660A9273F08B84E6A5E307D
public CdnEndpointImpl WithoutContentTypesToCompress()
{
if (Inner.ContentTypesToCompress != null)
{
Inner.ContentTypesToCompress.Clear();
}
return this;
}
///GENMHASH:69AE408B69EFE5C70BE2FFF8DAFDE487:E154C004F703949670CB42D405873DC1
public int HttpPort()
{
if (Inner.Origins != null && Inner.Origins.Any() &&
Inner.Origins.ElementAt(0).HttpPort.HasValue)
{
return Inner.Origins.ElementAt(0).HttpPort.Value;
}
else
{
return 0;
}
}
///GENMHASH:F2439439456B08DA8AB97215E07770D4:3B1EB2372D771F546AF6E37C78648BB2
public QueryStringCachingBehavior QueryStringCachingBehavior()
{
return Inner.QueryStringCachingBehavior.Value;
}
///GENMHASH:99D5BF64EA8AA0E287C9B6F77AAD6FC4:220D4662AAC7DF3BEFAF2B253278E85C
public string ProvisioningState()
{
return Inner.ProvisioningState;
}
///GENMHASH:03E80F0F2C9B94D8F1D6C59D199A324F:40C8D11EF6D101133A63F404CB1BB8D9
public CdnEndpointImpl WithoutGeoFilter(string relativePath)
{
if (Inner.GeoFilters != null && Inner.GeoFilters.Any())
{
var cleanList = Inner.GeoFilters
.Where(s => !s.RelativePath.Equals(relativePath, System.StringComparison.OrdinalIgnoreCase))
.ToList();
Inner.GeoFilters = cleanList;
}
return this;
}
///GENMHASH:D6FBED7FC7CBF34940541851FF5C3CC1:E911321F18C62EC3EB305DB02696CF08
public async Task StopAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await this.Parent.StopEndpointAsync(this.Name(), cancellationToken);
}
///GENMHASH:4432D0ADF52DD4D5E7DE90F40C6E8896:76F37D088A77DEC25DE11A157AB47F1D
public string OriginHostHeader()
{
return Inner.OriginHostHeader;
}
///GENMHASH:3660F0252470EA7E11BE799A78D9EC84:B7A7715C766EAE6ADE136666DFFE09AC
public bool IsHttpsAllowed()
{
return (Inner.IsHttpsAllowed.HasValue) ?
Inner.IsHttpsAllowed.Value : false;
}
///GENMHASH:B616A3CDCC5668DC239E5CB02EC9777C:8915C60D99E7BDD3A3FD9CF713070E1C
public string OptimizationType()
{
return Inner.OptimizationType;
}
///GENMHASH:339AE17292CFA9A95578C99FBDA11380:C16B6B3A2E90C698F4A188EF7462D6DC
public CdnEndpointImpl WithHttpsAllowed(bool httpsAllowed)
{
Inner.IsHttpsAllowed = httpsAllowed;
return this;
}
///GENMHASH:A50A011CA652E846C1780DCE98D171DE:1130E1FDC5A612FAE78D6B24DD71D43E
public string HostName()
{
return Inner.HostName;
}
///GENMHASH:0D2A82EC2942737570457A70F9912934:F9F8378CA5AE05C20515570CAE35960A
public string OriginHostName()
{
if (Inner.Origins != null && Inner.Origins.Any())
{
return Inner.Origins.ElementAt(0).HostName;
}
return null;
}
///GENMHASH:E60DC199BAC0D1A721C0F7662730ABA2:518C4F662A2D3826050A6374C08548F8
public string OriginPath()
{
return Inner.OriginPath;
}
///GENMHASH:BB5527D0B1FA45521F9A232A06597229:01B04246BADD46D49D939AF18D08E375
public CdnEndpointImpl WithContentTypesToCompress(ISet<string> contentTypesToCompress)
{
foreach (var contentType in contentTypesToCompress)
{
Inner.ContentTypesToCompress.Add(contentType);
}
return this;
}
///GENMHASH:1616938B44B8E0E6D22C3659A2BCFCFE:E3A9AC70C2F97D822D50254ECE662612
public int HttpsPort()
{
if (Inner.Origins != null && Inner.Origins.Any() &&
Inner.Origins.ElementAt(0).HttpsPort.HasValue)
{
return Inner.Origins.ElementAt(0).HttpsPort.Value;
}
return 0;
}
///GENMHASH:3883B65D38EC24BB4F7FD6D5BDD34433:6B89DE41199AB45D2C541D6B3DBC05CC
public CdnEndpointImpl WithGeoFilter(string relativePath, GeoFilterActions action, Microsoft.Azure.Management.ResourceManager.Fluent.Core.CountryISOCode countryCode)
{
var geoFilter = this.CreateGeoFiltersObject(relativePath, action);
if (geoFilter.CountryCodes == null)
{
geoFilter.CountryCodes = new List<string>();
}
geoFilter.CountryCodes.Add(countryCode.ToString());
Inner.GeoFilters.Add(geoFilter);
return this;
}
///GENMHASH:4FDE4EEEC9B63397B972B76FF764225E:9172F8EE25402A275A19C898977D3A0F
public CdnEndpointImpl WithGeoFilter(string relativePath, GeoFilterActions action, ICollection<Microsoft.Azure.Management.ResourceManager.Fluent.Core.CountryISOCode> countryCodes)
{
var geoFilter = this.CreateGeoFiltersObject(relativePath, action);
if (geoFilter.CountryCodes == null)
{
geoFilter.CountryCodes = new List<string>();
}
else
{
geoFilter.CountryCodes.Clear();
}
foreach (var countryCode in countryCodes)
{
geoFilter.CountryCodes.Add(countryCode.ToString());
}
Inner.GeoFilters.Add(geoFilter);
return this;
}
///GENMHASH:C7E3B6CC7CD3267F666A96B615DDC068:0357550555FFEA6B58DFA325B94D8DA2
public CdnEndpointImpl WithHttpPort(int httpPort)
{
if (Inner.Origins != null && Inner.Origins.Any())
{
Inner.Origins.ElementAt(0).HttpPort = httpPort;
}
return this;
}
///GENMHASH:02F4B346FD2A70C665ACC639FDB892A8:054BC4996D8D55194B78E5752276D4DE
public ISet<string> ContentTypesToCompress()
{
if (Inner.ContentTypesToCompress != null)
{
return new HashSet<string>(Inner.ContentTypesToCompress);
}
else
{
return new HashSet<string>();
}
}
///GENMHASH:E6BF4911DAC5A8F7935D5D2C29B496A4:5599AE7A8F08BDC419B9D9D6350D80B3
public CdnEndpointImpl WithoutCustomDomain(string hostName)
{
if (this.customDomainList != null && this.customDomainList.Any())
{
var cleanList = this.customDomainList
.Where(s =>
{
if (s.HostName.Equals(hostName, System.StringComparison.OrdinalIgnoreCase))
{
deletedCustomDomainList.Add(s);
return false;
}
return true;
})
.ToList();
this.customDomainList = cleanList;
}
return this;
}
///GENMHASH:C245F1873A239F9C8B080F237C995994:A795340EF45E36DBA21DC06A81CCDBD6
public ISet<string> CustomDomains()
{
return new HashSet<string>(customDomainList.Select(cd => cd.HostName));
}
///GENMHASH:23C4E65AB754D70B878D3A66AEE8E654:B3F227E77BD8D90C6C9A5BFB4BED56AB
public CdnEndpointImpl WithCompressionEnabled(bool compressionEnabled)
{
Inner.IsCompressionEnabled = compressionEnabled;
return this;
}
///GENMHASH:281727848C767EDFC12C710A13DB436B:BA8471CB595143B79C798EF5FFC865CC
public CdnEndpointImpl WithGeoFilters(ICollection<Microsoft.Azure.Management.Cdn.Fluent.Models.GeoFilter> geoFilters)
{
Inner.GeoFilters = geoFilters?.ToList();
return this;
}
///GENMHASH:077EB7776EFFBFAA141C1696E75EF7B3:34C3D97AC56EA49A0A7DE74A085B41B2
public CdnProfileImpl Attach()
{
return this.Parent.WithEndpoint(this);
}
///GENMHASH:57B9D4E7F982060F78F28F5609F2BC38:C49EB5D71E9039DEC17115C095E282F9
public CdnEndpointImpl WithHttpAllowed(bool httpAllowed)
{
Inner.IsHttpAllowed = httpAllowed;
return this;
}
///GENMHASH:CD6809DFDD78677C6753D833E44E73E6:8AB02C538F745324130F952F19B611D7
public bool IsHttpAllowed()
{
return (Inner.IsHttpAllowed.HasValue) ?
Inner.IsHttpAllowed.Value : false;
}
///GENMHASH:D5AD274A3026D80CDF6A0DD97D9F20D4:C432CD0FA5ECF4FD2A5B42F0A5769FF8
public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await this.Parent.StartEndpointAsync(this.Name(), cancellationToken);
}
///GENMHASH:5A2D79502EDA81E37A36694062AEDC65:FA3619AB1196A3C6CA363F9680EFB908
public override async Task<ICdnEndpoint> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken))
{
EndpointInner inner = await GetInnerAsync(cancellationToken);
SetInner(inner);
customDomainList.Clear();
deletedCustomDomainList.Clear();
customDomainList.AddRange(
Extensions.Synchronize(() => Parent.Manager.Inner.CustomDomains.ListByEndpointAsync(
Parent.ResourceGroupName,
Parent.Name,
Name())));
return this;
}
///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:2146F0F4C035C1D53CB5A84619CB4F7E
protected override async Task<EndpointInner> GetInnerAsync(CancellationToken cancellationToken)
{
return await Parent.Manager.Inner.Endpoints.GetAsync(
Parent.ResourceGroupName,
Parent.Name,
Name(), cancellationToken: cancellationToken);
}
///GENMHASH:64AF8E4C0DC21702ECEBDAB60ABF9E38:B0E2487AEAA046DB40AFBF76759F57B7
public CdnEndpointImpl WithoutGeoFilters()
{
if (Inner.GeoFilters != null)
{
Inner.GeoFilters.Clear();
}
return this;
}
///GENMHASH:0FEDA307DAD2022B36843E8905D26EAD:1FCADA6725C3703873C98FE44F5EB8D1
public async override Task DeleteAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await Parent.Manager.Inner.Endpoints.DeleteAsync(
Parent.ResourceGroupName,
Parent.Name,
Name(),
cancellationToken);
}
///GENMHASH:ED6AC52E4E80AB09EC1F1A4F7D67B43D:1304F5065C963D2A0B0FDB3559616C62
public bool IsCompressionEnabled()
{
return (Inner.IsCompressionEnabled.HasValue) ?
Inner.IsCompressionEnabled.Value : false;
}
///GENMHASH:D3FBCD749DB493DA3ADF137746D72E03:9DBDBE523213D7A819804C9FDF7A21BF
internal CdnEndpointImpl(string name, CdnProfileImpl parent, EndpointInner inner)
: base(name, parent, inner)
{
customDomainList = new List<CustomDomainInner>();
deletedCustomDomainList = new List<CustomDomainInner>();
}
///GENMHASH:D318AAF0AF67937A3B0D7457810D7189:9C29B8395D3F24B9173B3136ACF366A7
public CdnEndpointImpl WithoutContentTypeToCompress(string contentTypeToCompress)
{
if (Inner.ContentTypesToCompress != null)
{
Inner.ContentTypesToCompress.Remove(contentTypeToCompress);
}
return this;
}
///GENMHASH:693BE444A3B7607A943975559DB607E2:06BF95A95E70AE38A4CDD5D6B5F142E7
public CdnEndpointImpl WithOriginPath(string originPath)
{
Inner.OriginPath = originPath;
return this;
}
///GENMHASH:79A840C9F24220C8EF02C0B73BAD3C0F:3586CFD7AEFDBFA89168B9EFC6A2C18C
private GeoFilter CreateGeoFiltersObject(string relativePath, GeoFilterActions action)
{
if (Inner.GeoFilters == null)
{
Inner.GeoFilters = new List<GeoFilter>();
}
var geoFilter = Inner.GeoFilters
.FirstOrDefault(s => s.RelativePath.Equals(
relativePath,
System.StringComparison.OrdinalIgnoreCase));
if (geoFilter == null)
{
geoFilter = new GeoFilter();
}
else
{
Inner.GeoFilters.Remove(geoFilter);
}
geoFilter.RelativePath = relativePath;
geoFilter.Action = action;
return geoFilter;
}
///GENMHASH:870B1F6CF318C295B15B16948090E5A0:ABEA6A4F088942CBF4A75A3B05559004
public CdnEndpointImpl WithCustomDomain(string hostName)
{
if (this.customDomainList == null)
{
this.customDomainList = new List<CustomDomainInner>();
}
this.customDomainList.Add(new CustomDomainInner
{
HostName = hostName
});
return this;
}
///GENMHASH:7CB89D7FE550C78D7CC8178691681D0D:94F4EC251039F7DE8ADA1C48DB8FC42A
public async Task<CustomDomainValidationResult> ValidateCustomDomainAsync(
string hostName,
CancellationToken cancellationToken = default(CancellationToken))
{
return await this.Parent.ValidateEndpointCustomDomainAsync(this.Name(), hostName, cancellationToken);
}
///GENMHASH:89CD44AA5060CAB16CB0AF1FB046BC64:0A693DB1A3AF2F29E579F4E675DE54E9
public IEnumerable<ResourceUsage> ListResourceUsage()
{
return Extensions.Synchronize(() => Parent.Manager.Inner.Endpoints.ListResourceUsageInnerAsync(
Parent.ResourceGroupName,
Parent.Name,
Name()))
.AsContinuousCollection(link => Extensions.Synchronize(() => Parent.Manager.Inner.Endpoints.ListResourceUsageInnerNextAsync(link)))
.Select(inner => new ResourceUsage(inner));
}
IUpdate ISettable<IUpdate>.Parent()
{
return this.Parent;
}
}
}
| |
using System;
using System.IO;
using NuGet;
using Orchard.ContentManagement;
using Orchard.Environment.Extensions;
using Orchard.Environment.Extensions.Models;
using Orchard.FileSystems.VirtualPath;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Packaging.Extensions;
using Orchard.Packaging.Models;
using Orchard.UI;
using Orchard.UI.Notify;
using NuGetPackageManager = NuGet.PackageManager;
namespace Orchard.Packaging.Services {
[OrchardFeature("PackagingServices")]
public class PackageInstaller : IPackageInstaller {
private const string PackagesPath = "packages";
private const string SolutionFilename = "Orchard.sln";
private readonly INotifier _notifier;
private readonly IVirtualPathProvider _virtualPathProvider;
private readonly IExtensionManager _extensionManager;
private readonly IFolderUpdater _folderUpdater;
public PackageInstaller(
INotifier notifier,
IVirtualPathProvider virtualPathProvider,
IExtensionManager extensionManager,
IFolderUpdater folderUpdater) {
_notifier = notifier;
_virtualPathProvider = virtualPathProvider;
_extensionManager = extensionManager;
_folderUpdater = folderUpdater;
T = NullLocalizer.Instance;
Logger = Logging.NullLogger.Instance;
}
public Localizer T { get; set; }
public Logging.ILogger Logger { get; set; }
public PackageInfo Install(string packageId, string version, string location, string applicationPath) {
// instantiates the appropriate package repository
IPackageRepository packageRepository = PackageRepositoryFactory.Default.CreateRepository(new PackageSource(location, "Default"));
// gets an IPackage instance from the repository
var packageVersion = String.IsNullOrEmpty(version) ? null : new Version(version);
var package = packageRepository.FindPackage(packageId, packageVersion);
if (package == null) {
throw new ArgumentException(T("The specified package could not be found, id:{0} version:{1}", packageId, String.IsNullOrEmpty(version) ? T("No version").Text : version).Text);
}
return InstallPackage(package, packageRepository, location, applicationPath);
}
public PackageInfo Install(IPackage package, string location, string applicationPath) {
// instantiates the appropriate package repository
IPackageRepository packageRepository = PackageRepositoryFactory.Default.CreateRepository(new PackageSource(location, "Default"));
return InstallPackage(package, packageRepository, location, applicationPath);
}
protected PackageInfo InstallPackage(IPackage package, IPackageRepository packageRepository, string location, string applicationPath) {
bool previousInstalled;
// 1. See if extension was previous installed and backup its folder if so
try {
previousInstalled = BackupExtensionFolder(package.ExtensionFolder(), package.ExtensionId());
}
catch (Exception exception) {
throw new OrchardException(T("Unable to backup existing local package directory."), exception);
}
if (previousInstalled) {
// 2. If extension is installed, need to un-install first
try {
UninstallExtensionIfNeeded(package);
}
catch (Exception exception) {
throw new OrchardException(T("Unable to un-install local package before updating."), exception);
}
}
var packageInfo = ExecuteInstall(package, packageRepository, location, applicationPath);
// check the new package is compatible with current Orchard version
var descriptor = package.GetExtensionDescriptor(packageInfo.ExtensionType);
if(descriptor != null) {
if(new FlatPositionComparer().Compare(descriptor.OrchardVersion, typeof(ContentItem).Assembly.GetName().Version.ToString()) >= 0) {
if (previousInstalled) {
// restore the previous version
RestoreExtensionFolder(package.ExtensionFolder(), package.ExtensionId());
}
else {
// just uninstall the new package
Uninstall(package.Id, _virtualPathProvider.MapPath("~\\"));
}
Logger.Error(String.Format("The package is compatible with version {0} and above. Please update Orchard or install another version of this package.", descriptor.OrchardVersion));
throw new OrchardException(T("The package is compatible with version {0} and above. Please update Orchard or install another version of this package.", descriptor.OrchardVersion));
}
}
return packageInfo;
}
/// <summary>
/// Executes a package installation.
/// </summary>
/// <param name="package">The package to install.</param>
/// <param name="packageRepository">The repository for the package.</param>
/// <param name="sourceLocation">The source location.</param>
/// <param name="targetPath">The path where to install the package.</param>
/// <returns>The package information.</returns>
protected PackageInfo ExecuteInstall(IPackage package, IPackageRepository packageRepository, string sourceLocation, string targetPath) {
// this logger is used to render NuGet's log on the notifier
var logger = new NugetLogger(_notifier);
bool installed = false;
// if we can access the parent directory, and the solution is inside, NuGet-install the package here
string solutionPath;
var installedPackagesPath = String.Empty;
if (TryGetSolutionPath(targetPath, out solutionPath)) {
installedPackagesPath = Path.Combine(solutionPath, PackagesPath);
try {
var packageManager = new NuGetPackageManager(
packageRepository,
new DefaultPackagePathResolver(sourceLocation),
new PhysicalFileSystem(installedPackagesPath) {Logger = logger}
) {Logger = logger};
packageManager.InstallPackage(package, true);
installed = true;
}
catch {
// installing the package at the solution level failed
}
}
// if the package got installed successfully, use it, otherwise use the previous repository
var sourceRepository = installed
? new LocalPackageRepository(installedPackagesPath)
: packageRepository;
var project = new FileBasedProjectSystem(targetPath) { Logger = logger };
var projectManager = new ProjectManager(
sourceRepository, // source repository for the package to install
new DefaultPackagePathResolver(targetPath),
project,
new ExtensionReferenceRepository(project, sourceRepository, _extensionManager)
) { Logger = logger };
// add the package to the project
projectManager.AddPackageReference(package.Id, package.Version);
return new PackageInfo {
ExtensionName = package.Title ?? package.Id,
ExtensionVersion = package.Version.ToString(),
ExtensionType = package.Id.StartsWith(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Theme)) ? DefaultExtensionTypes.Theme : DefaultExtensionTypes.Module,
ExtensionPath = targetPath
};
}
/// <summary>
/// Uninstalls a package.
/// </summary>
/// <param name="packageId">The package identifier for the package to be uninstalled.</param>
/// <param name="applicationPath">The application path.</param>
public void Uninstall(string packageId, string applicationPath) {
string solutionPath;
string extensionFullPath = string.Empty;
if (packageId.StartsWith(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Theme))) {
extensionFullPath = _virtualPathProvider.MapPath("~/Themes/" + packageId.Substring(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Theme).Length));
} else if (packageId.StartsWith(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Module))) {
extensionFullPath = _virtualPathProvider.MapPath("~/Modules/" + packageId.Substring(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Module).Length));
}
if (string.IsNullOrEmpty(extensionFullPath) ||
!Directory.Exists(extensionFullPath)) {
throw new OrchardException(T("Package not found: {0}", packageId));
}
// if we can access the parent directory, and the solution is inside, NuGet-uninstall the package here
if (TryGetSolutionPath(applicationPath, out solutionPath)) {
// this logger is used to render NuGet's log on the notifier
var logger = new NugetLogger(_notifier);
var installedPackagesPath = Path.Combine(solutionPath, PackagesPath);
var sourcePackageRepository = new LocalPackageRepository(installedPackagesPath);
try {
var project = new FileBasedProjectSystem(applicationPath) {Logger = logger};
var projectManager = new ProjectManager(
sourcePackageRepository,
new DefaultPackagePathResolver(installedPackagesPath),
project,
new ExtensionReferenceRepository(project, sourcePackageRepository, _extensionManager)
) {Logger = logger};
// add the package to the project
projectManager.RemovePackageReference(packageId);
}
catch {
// Uninstalling the package at the solution level failed
}
try {
var packageManager = new NuGetPackageManager(
sourcePackageRepository,
new DefaultPackagePathResolver(applicationPath),
new PhysicalFileSystem(installedPackagesPath) {Logger = logger}
) {Logger = logger};
packageManager.UninstallPackage(packageId);
}
catch {
// Package doesnt exist anymore
}
}
// If the package was not installed through nuget we still need to try to uninstall it by removing its directory
if (Directory.Exists(extensionFullPath)) {
Directory.Delete(extensionFullPath, true);
}
}
private static bool TryGetSolutionPath(string applicationPath, out string parentPath) {
try {
parentPath = Directory.GetParent(applicationPath).Parent.FullName;
var solutionPath = Path.Combine(parentPath, SolutionFilename);
return File.Exists(solutionPath);
}
catch {
// Either solution does not exist or we are running under medium trust
parentPath = null;
return false;
}
}
private bool RestoreExtensionFolder(string extensionFolder, string extensionId) {
var source = new DirectoryInfo(_virtualPathProvider.MapPath(_virtualPathProvider.Combine("~", extensionFolder, extensionId)));
if (source.Exists) {
var tempPath = _virtualPathProvider.Combine("~", extensionFolder, "_Backup", extensionId);
string localTempPath = null;
for (int i = 0; i < 1000; i++) {
localTempPath = _virtualPathProvider.MapPath(tempPath) + (i == 0 ? "" : "." + i.ToString());
if (!Directory.Exists(localTempPath)) {
Directory.CreateDirectory(localTempPath);
break;
}
localTempPath = null;
}
if (localTempPath == null) {
throw new OrchardException(T("Backup folder {0} has too many backups subfolder (limit is 1,000)", tempPath));
}
var backupFolder = new DirectoryInfo(localTempPath);
_folderUpdater.Restore(backupFolder, source);
_notifier.Information(T("Successfully restored local package to local folder \"{0}\"", source));
return true;
}
return false;
}
private bool BackupExtensionFolder(string extensionFolder, string extensionId) {
var source = new DirectoryInfo(_virtualPathProvider.MapPath(_virtualPathProvider.Combine("~", extensionFolder, extensionId)));
if (source.Exists) {
var tempPath = _virtualPathProvider.Combine("~", extensionFolder, "_Backup", extensionId);
string localTempPath = null;
for (int i = 0; i < 1000; i++) {
localTempPath = _virtualPathProvider.MapPath(tempPath) + (i == 0 ? "" : "." + i.ToString());
if (!Directory.Exists(localTempPath)) {
Directory.CreateDirectory(localTempPath);
break;
}
localTempPath = null;
}
if (localTempPath == null) {
throw new OrchardException(T("Backup folder {0} has too many backups subfolder (limit is 1,000)", tempPath));
}
var backupFolder = new DirectoryInfo(localTempPath);
_folderUpdater.Backup(source, backupFolder);
_notifier.Information(T("Successfully backed up local package to local folder \"{0}\"", backupFolder));
return true;
}
return false;
}
private void UninstallExtensionIfNeeded(IPackage package) {
// Nuget requires to un-install the currently installed packages if the new
// package is the same version or an older version
try {
Uninstall(package.Id, _virtualPathProvider.MapPath("~\\"));
_notifier.Information(T("Successfully un-installed local package {0}", package.ExtensionId()));
}
catch {}
}
}
}
| |
/*
* CID0023.cs - be culture handler.
*
* Copyright (c) 2003 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "be.txt".
namespace I18N.Other
{
using System;
using System.Globalization;
using I18N.Common;
public class CID0023 : RootCulture
{
public CID0023() : base(0x0023) {}
public CID0023(int culture) : base(culture) {}
public override String Name
{
get
{
return "be";
}
}
public override String ThreeLetterISOLanguageName
{
get
{
return "bel";
}
}
public override String ThreeLetterWindowsLanguageName
{
get
{
return "BEL";
}
}
public override String TwoLetterISOLanguageName
{
get
{
return "be";
}
}
public override DateTimeFormatInfo DateTimeFormat
{
get
{
DateTimeFormatInfo dfi = base.DateTimeFormat;
dfi.AbbreviatedDayNames = new String[] {"\u043d\u0434", "\u043F\u043D", "\u0430\u045e", "\u0441\u0440", "\u0447\u0446", "\u043F\u0442", "\u0441\u0431"};
dfi.DayNames = new String[] {"\u043D\u044F\u0434\u0437\u0435\u043B\u044F", "\u043F\u0430\u043D\u044F\u0434\u0437\u0435\u043B\u0430\u043A", "\u0430\u045E\u0442\u043E\u0440\u0430\u043A", "\u0441\u0435\u0440\u0430\u0434\u0430", "\u0447\u0430\u0446\u0432\u0435\u0440", "\u043F\u044F\u0442\u043D\u0456\u0446\u0430", "\u0441\u0443\u0431\u043E\u0442\u0430"};
dfi.AbbreviatedMonthNames = new String[] {"\u0421\u0442\u0443", "\u041b\u044e\u0442", "\u0421\u0430\u043a", "\u041a\u0440\u0430", "\u041c\u0430\u0439", "\u0427\u044d\u0440", "\u041b\u0456\u043f", "\u0416\u043d\u0456", "\u0412\u0435\u0440", "\u041a\u0430\u0441", "\u041b\u0456\u0441", "\u0421\u043d\u0435", ""};
dfi.MonthNames = new String[] {"\u0421\u0442\u0443\u0434\u0437\u0435\u043d\u044c", "\u041b\u044e\u0442\u044b", "\u0421\u0430\u043a\u0430\u0432\u0456\u043a", "\u041a\u0440\u0430\u0441\u0430\u0432\u0456\u043a", "\u041c\u0430\u0439", "\u0427\u044d\u0440\u0432\u0435\u043d\u044c", "\u041b\u0456\u043f\u0435\u043d\u044c", "\u0416\u043d\u0456\u0432\u0435\u043d\u044c", "\u0412\u0435\u0440\u0430\u0441\u0435\u043d\u044c", "\u041a\u0430\u0441\u0442\u0440\u044b\u0447\u043d\u0456\u043a", "\u041b\u0456\u0441\u0442\u0430\u043f\u0430\u0434", "\u0421\u043d\u0435\u0436\u0430\u043d\u044c", ""};
dfi.DateSeparator = ".";
dfi.TimeSeparator = ".";
dfi.LongDatePattern = "d MMMM yyyy";
dfi.LongTimePattern = "HH.mm.ss z";
dfi.ShortDatePattern = "d.M.yy";
dfi.ShortTimePattern = "HH.mm";
dfi.FullDateTimePattern = "dddd, d MMMM yyyy HH.mm.ss z";
dfi.I18NSetDateTimePatterns(new String[] {
"d:d.M.yy",
"D:dddd, d MMMM yyyy",
"f:dddd, d MMMM yyyy HH.mm.ss z",
"f:dddd, d MMMM yyyy HH.mm.ss z",
"f:dddd, d MMMM yyyy HH.mm.ss",
"f:dddd, d MMMM yyyy HH.mm",
"F:dddd, d MMMM yyyy HH.mm.ss",
"g:d.M.yy HH.mm.ss z",
"g:d.M.yy HH.mm.ss z",
"g:d.M.yy HH.mm.ss",
"g:d.M.yy HH.mm",
"G:d.M.yy HH.mm.ss",
"m:MMMM dd",
"M:MMMM dd",
"r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
"s:yyyy'-'MM'-'dd'T'HH':'mm':'ss",
"t:HH.mm.ss z",
"t:HH.mm.ss z",
"t:HH.mm.ss",
"t:HH.mm",
"T:HH.mm.ss",
"u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
"U:dddd, dd MMMM yyyy HH:mm:ss",
"y:yyyy MMMM",
"Y:yyyy MMMM",
});
return dfi;
}
set
{
base.DateTimeFormat = value; // not used
}
}
public override NumberFormatInfo NumberFormat
{
get
{
NumberFormatInfo nfi = base.NumberFormat;
nfi.CurrencyDecimalSeparator = ",";
nfi.CurrencyGroupSeparator = "\u00A0";
nfi.NumberGroupSeparator = "\u00A0";
nfi.PercentGroupSeparator = "\u00A0";
nfi.NegativeSign = "-";
nfi.NumberDecimalSeparator = ",";
nfi.PercentDecimalSeparator = ",";
nfi.PercentSymbol = "%";
nfi.PerMilleSymbol = "\u2030";
return nfi;
}
set
{
base.NumberFormat = value; // not used
}
}
public override String ResolveLanguage(String name)
{
switch(name)
{
case "be": return "\u0411\u0435\u043B\u0430\u0440\u0443\u0441\u043A\u0456";
}
return base.ResolveLanguage(name);
}
public override String ResolveCountry(String name)
{
switch(name)
{
case "BY": return "\u0411\u0435\u043B\u0430\u0440\u0443\u0441\u044C";
}
return base.ResolveCountry(name);
}
private class PrivateTextInfo : _I18NTextInfo
{
public PrivateTextInfo(int culture) : base(culture) {}
public override int ANSICodePage
{
get
{
return 1251;
}
}
public override int EBCDICCodePage
{
get
{
return 500;
}
}
public override int MacCodePage
{
get
{
return 10007;
}
}
public override int OEMCodePage
{
get
{
return 866;
}
}
public override String ListSeparator
{
get
{
return ";";
}
}
}; // class PrivateTextInfo
public override TextInfo TextInfo
{
get
{
return new PrivateTextInfo(LCID);
}
}
}; // class CID0023
public class CNbe : CID0023
{
public CNbe() : base() {}
}; // class CNbe
}; // namespace I18N.Other
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MySecondWebApp.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Security.Authentication;
namespace System.Net.Mail
{
internal enum PropertyName
{
Invalid = 0,
ServerState = 1016,
PickupDirectory = 36880
};
internal enum ServerState
{
Starting = 1,
Started = 2,
Stopping = 3,
Stopped = 4,
Pausing = 5,
Paused = 6,
Continuing = 7,
}
internal enum MBErrors
{
DataNotFound = unchecked( (int)0x800CC801 ), // MD_ERROR_DATA_NOT_FOUND
InvalidVersion = unchecked( (int)0x800CC802 ), // MD_ERROR_INVALID_VERSION
DuplicateNameWarning = unchecked( (int)0x000CC804 ), // MD_WARNING_DUP_NAME
InvalidDataWarning = unchecked( (int)0x000CC805 ), // MD_WARNING_INVALID_DATA
AlreadyExists = unchecked( (int)0x800700B7 ), // RETURNCODETOHRESULT( ERROR_ALREADY_EXISTS )
InvalidParameter = unchecked( (int)0x80070057 ), // E_INVALIDARG
PathNotFound = unchecked( (int)0x80070003 ), // RETURNCODETOHRESULT( ERROR_PATH_NOT_FOUND )
PathBusy = unchecked( (int)0x80070094 ), // RETURNCODETOHRESULT( ERROR_PATH_BUSY )
InsufficientBuffer = unchecked( (int)0x8007007A ), // RETURNCODETOHRESULT( ERROR_INSUFFICIENT_BUFFER )
NoMoreItems = unchecked( (int)0x80070103 ), // RETURNCODETOHRESULT( ERROR_NO_MORE_ITEMS )
AccessDenied = unchecked( (int)0x80070005 ), // RETURNCODETOHRESULT( E_ACCCESS_DENIED )
};
[Flags]
internal enum MBKeyAccess : uint
{
Read = 1,
Write = 2
};
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
internal unsafe struct MetadataRecord
{
internal UInt32 Identifier;
internal UInt32 Attributes;
internal UInt32 UserType;
internal UInt32 DataType;
internal UInt32 DataLen;
internal IntPtr DataBuf;
internal UInt32 DataTag;
};
[StructLayout(LayoutKind.Sequential)]
internal class _METADATA_HANDLE_INFO
{
_METADATA_HANDLE_INFO()
{
dwMDPermissions = 0;
dwMDSystemChangeNumber = 0;
}
internal Int32 dwMDPermissions;
internal Int32 dwMDSystemChangeNumber;
};
#region IMSadminBase itf definitions
/// <summary>
/// Summary description for Class1.
/// </summary>
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport, Guid("70b51430-b6ca-11d0-b9b9-00a0c922e750")]
internal interface IMSAdminBase
{
[PreserveSig]
int AddKey(
IntPtr handle,
[MarshalAs(UnmanagedType.LPWStr)] string Path
);
[PreserveSig]
int DeleteKey(
IntPtr handle,
[MarshalAs(UnmanagedType.LPWStr)] string Path
);
void DeleteChildKeys(
IntPtr handle,
[MarshalAs(UnmanagedType.LPWStr)] string Path
);
[PreserveSig]
int EnumKeys(
IntPtr handle,
[MarshalAs(UnmanagedType.LPWStr)] string Path,
StringBuilder Buffer,
int EnumKeyIndex
);
void CopyKey(
IntPtr source,
[MarshalAs(UnmanagedType.LPWStr)] string SourcePath,
IntPtr dest,
[MarshalAs(UnmanagedType.LPWStr)] string DestPath,
bool OverwriteFlag,
bool CopyFlag
);
void RenameKey(
IntPtr key,
[MarshalAs(UnmanagedType.LPWStr)] string path,
[MarshalAs(UnmanagedType.LPWStr)] string newName
);
[PreserveSig]
int SetData(
IntPtr key,
[MarshalAs(UnmanagedType.LPWStr)] string path,
ref MetadataRecord data
);
[PreserveSig]
int GetData(
IntPtr key,
[MarshalAs(UnmanagedType.LPWStr)] string path,
ref MetadataRecord data,
[In, Out] ref uint RequiredDataLen
);
[PreserveSig]
int DeleteData(
IntPtr key,
[MarshalAs(UnmanagedType.LPWStr)] string path,
uint Identifier,
uint DataType
);
[PreserveSig]
int EnumData(
IntPtr key,
[MarshalAs(UnmanagedType.LPWStr)] string path,
ref MetadataRecord data,
int EnumDataIndex,
[In, Out] ref uint RequiredDataLen
);
[PreserveSig]
int GetAllData(
IntPtr handle,
[MarshalAs(UnmanagedType.LPWStr)] string Path,
UInt32 Attributes,
UInt32 UserType,
UInt32 DataType,
[In, Out] ref UInt32 NumDataEntries,
[In, Out] ref UInt32 DataSetNumber,
UInt32 BufferSize,
// [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=7)] out byte[] Buffer,
IntPtr buffer,
[In,Out] ref UInt32 RequiredBufferSize
);
void DeleteAllData(
IntPtr handle,
[MarshalAs(UnmanagedType.LPWStr)] string Path,
uint UserType,
uint DataType
);
[PreserveSig]
int CopyData(
IntPtr sourcehandle,
[MarshalAs(UnmanagedType.LPWStr)] string SourcePath,
IntPtr desthandle,
[MarshalAs(UnmanagedType.LPWStr)] string DestPath,
int Attributes,
int UserType,
int DataType,
[MarshalAs(UnmanagedType.Bool)] bool CopyFlag
);
[PreserveSig]
void GetDataPaths(
IntPtr handle,
[MarshalAs(UnmanagedType.LPWStr)] string Path,
int Identifier,
int DataType,
int BufferSize,
[Out, MarshalAs(UnmanagedType.LPWStr, SizeParamIndex=4)] out char[] Buffer,
[In, Out, MarshalAs(UnmanagedType.U4)] ref int RequiredBufferSize
);
[PreserveSig]
int OpenKey(
IntPtr handle,
[MarshalAs(UnmanagedType.LPWStr)] string Path,
[MarshalAs(UnmanagedType.U4)] MBKeyAccess AccessRequested,
int TimeOut,
[In, Out] ref IntPtr NewHandle
);
[PreserveSig]
int CloseKey(
IntPtr handle
);
void ChangePermissions(
IntPtr handle,
int TimeOut,
[MarshalAs(UnmanagedType.U4)] MBKeyAccess AccessRequested
);
void SaveData(
);
[PreserveSig]
void GetHandleInfo(
IntPtr handle,
[In, Out] ref _METADATA_HANDLE_INFO Info
);
[PreserveSig]
void GetSystemChangeNumber(
[In, Out, MarshalAs(UnmanagedType.U4)] ref uint SystemChangeNumber
);
[PreserveSig]
void GetDataSetNumber(
IntPtr handle,
[MarshalAs(UnmanagedType.LPWStr)] string Path,
[In, Out] ref uint DataSetNumber
);
[PreserveSig]
void SetLastChangeTime(
IntPtr handle,
[MarshalAs(UnmanagedType.LPWStr)] string Path,
[Out] out System.Runtime.InteropServices.ComTypes.FILETIME LastChangeTime,
bool LocalTime
);
[PreserveSig]
int GetLastChangeTime(
IntPtr handle,
[MarshalAs(UnmanagedType.LPWStr)] string Path,
[In, Out] ref System.Runtime.InteropServices.ComTypes.FILETIME LastChangeTime,
bool LocalTime
);
[PreserveSig]
int KeyExchangePhase1(
);
[PreserveSig]
int KeyExchangePhase2(
);
[PreserveSig]
int Backup(
[MarshalAs(UnmanagedType.LPWStr)] string Location,
int Version,
int Flags
);
[PreserveSig]
int Restore(
[MarshalAs(UnmanagedType.LPWStr)] string Location,
int Version,
int Flags
);
[PreserveSig]
void EnumBackups(
[Out, MarshalAs(UnmanagedType.LPWStr, SizeConst=256)] out string Location,
[Out, MarshalAs(UnmanagedType.U4)] out uint Version,
[Out] out System.Runtime.InteropServices.ComTypes.FILETIME BackupTime,
uint EnumIndex
);
[PreserveSig]
void DeleteBackup(
[MarshalAs(UnmanagedType.LPWStr)] string Location,
int Version
);
[PreserveSig]
int UnmarshalInterface(
[Out] [MarshalAs(UnmanagedType.Interface)] out IMSAdminBase interf
);
[PreserveSig]
int GetServerGuid(
);
}
[ClassInterface(ClassInterfaceType.None)]
[TypeLibType(TypeLibTypeFlags.FCanCreate)]
[ComImport, Guid("a9e69610-b80d-11d0-b9b9-00a0c922e750")]
internal class MSAdminBase
{
}
#endregion
internal enum MBDataType : byte
{
All = 0,
Dword = 1,
String = 2,
Binary = 3,
StringExpand = 4,
MultiString = 5
};
internal enum MBUserType : byte
{
Other = 0,
Asp = 101, // ASP_MD_UT_APP,
File = 2, // IIS_MD_UT_FILE,
Server = 1, // IIS_MD_UT_SERVER,
Wam = 100 // IIS_MD_UT_WAM
};
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
internal static class IisPickupDirectory
{
const int MaxPathSize = 260;
const int InfiniteTimeout = -1;
const int MetadataMaxNameLen = 256;
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal unsafe static string GetPickupDirectory()
{
int hr;
UInt32 reqLength=0;
Int32 serverState;
string pickupDirectory=string.Empty;
IMSAdminBase adminBase = null;
IntPtr ptrKey = IntPtr.Zero;
StringBuilder keySuffix = new StringBuilder(MetadataMaxNameLen);
uint bufferLen = MaxPathSize * 4;
byte[] buffer = new byte[bufferLen];
try {
adminBase = new MSAdminBase() as IMSAdminBase;
hr = adminBase.OpenKey(IntPtr.Zero, "LM/SmtpSvc", MBKeyAccess.Read, InfiniteTimeout, ref ptrKey);
if (hr < 0)
goto Exit;
MetadataRecord rec = new MetadataRecord();
fixed( byte* bufferPtr = buffer)
{
for (int index=0; ; index++)
{
hr = adminBase.EnumKeys(ptrKey, "", keySuffix, index);
if (hr == unchecked((int)MBErrors.NoMoreItems))
break;
if (hr < 0)
goto Exit;
rec.Identifier = (UInt32) PropertyName.ServerState;
rec.Attributes = 0;
rec.UserType = (UInt32) MBUserType.Server;
rec.DataType = (UInt32) MBDataType.Dword;
rec.DataTag = 0;
rec.DataBuf = (IntPtr) bufferPtr;
rec.DataLen = bufferLen;
hr = adminBase.GetData(ptrKey, keySuffix.ToString(), ref rec, ref reqLength);
if (hr < 0)
{
if (hr == unchecked((int)MBErrors.DataNotFound) ||
hr == unchecked((int)MBErrors.AccessDenied))
continue;
else
goto Exit;
}
serverState = Marshal.ReadInt32((IntPtr)bufferPtr);
if (serverState == (Int32) ServerState.Started)
{
rec.Identifier = (UInt32) PropertyName.PickupDirectory;
rec.Attributes = 0;
rec.UserType = (UInt32) MBUserType.Server;
rec.DataType = (UInt32) MBDataType.String;
rec.DataTag = 0;
rec.DataBuf = (IntPtr) bufferPtr;
rec.DataLen = bufferLen;
hr = adminBase.GetData(ptrKey, keySuffix.ToString(), ref rec, ref reqLength);
if (hr < 0)
goto Exit;
pickupDirectory = Marshal.PtrToStringUni((IntPtr)bufferPtr);
break;
}
}
if (hr == unchecked((int)MBErrors.NoMoreItems))
{
for (int index=0; ; index++)
{
hr = adminBase.EnumKeys(ptrKey, "", keySuffix, index);
if (hr == unchecked((int)MBErrors.NoMoreItems))
break;
if (hr < 0)
goto Exit;
rec.Identifier = (UInt32) PropertyName.PickupDirectory;
rec.Attributes = 0;
rec.UserType = (UInt32) MBUserType.Server;
rec.DataType = (UInt32) MBDataType.String;
rec.DataTag = 0;
rec.DataBuf = (IntPtr) bufferPtr;
rec.DataLen = bufferLen;
hr = adminBase.GetData(ptrKey, keySuffix.ToString(), ref rec, ref reqLength);
if (hr < 0)
{
if (hr == unchecked((int)MBErrors.DataNotFound) ||
hr == unchecked((int)MBErrors.AccessDenied))
continue;
else
goto Exit;
}
pickupDirectory = Marshal.PtrToStringUni((IntPtr)bufferPtr);
if (Directory.Exists(pickupDirectory))
break;
else
pickupDirectory = string.Empty;
}
}
}
Exit:
;
}
catch (Exception exception) {
if (exception is SecurityException ||
exception is AuthenticationException ||
exception is SmtpException)
throw;
throw new SmtpException(SR.GetString(SR.SmtpGetIisPickupDirectoryFailed));
}
finally {
if (adminBase != null)
if (ptrKey != IntPtr.Zero)
adminBase.CloseKey(ptrKey);
}
if (pickupDirectory == string.Empty)
throw new SmtpException(SR.GetString(SR.SmtpGetIisPickupDirectoryFailed));
return pickupDirectory;
}
}
}
| |
// Prexonite
//
// Copyright (c) 2014, Christian Klauser
// 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.
// The names of the 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.
#region
using System;
using Prexonite.Compiler.Cil;
#endregion
namespace Prexonite.Types
{
[PTypeLiteral("Real")]
public class RealPType : PType, ICilCompilerAware
{
#region Singleton pattern
private static readonly RealPType instance;
public static RealPType Instance
{
get { return instance; }
}
static RealPType()
{
instance = new RealPType();
}
private RealPType()
{
}
#endregion
#region Static
public PValue CreatePValue(double value)
{
return new PValue(value, Instance);
}
public PValue CreatePValue(float value)
{
return new PValue((double) value, Instance);
}
#endregion
#region Access interface implementation
public override bool TryConstruct(StackContext sctx, PValue[] args, out PValue result)
{
if (args.Length <= 1)
{
result = Real.CreatePValue(0.0);
return true;
}
return args[0].TryConvertTo(sctx, Real, out result);
}
public override bool TryDynamicCall(
StackContext sctx,
PValue subject,
PValue[] args,
PCall call,
string id,
out PValue result)
{
Object[typeof (double)].TryDynamicCall(sctx, subject, args, call, id, out result);
return result != null;
}
public override bool TryStaticCall(
StackContext sctx, PValue[] args, PCall call, string id, out PValue result)
{
Object[typeof (double)].TryStaticCall(sctx, args, call, id, out result);
return result != null;
}
protected override bool InternalConvertTo(
StackContext sctx,
PValue subject,
PType target,
bool useExplicit,
out PValue result)
{
result = null;
if (useExplicit)
{
if (target is ObjectPType)
{
switch (Type.GetTypeCode(((ObjectPType) target).ClrType))
{
case TypeCode.Byte:
result = CreateObject((Byte) (Double) subject.Value);
break;
case TypeCode.SByte:
result = CreateObject((SByte) (Double) subject.Value);
break;
case TypeCode.Int32:
result = CreateObject((Int32) (Double) subject.Value);
break;
case TypeCode.UInt32:
result = CreateObject((UInt32) (Double) subject.Value);
break;
case TypeCode.Int16:
result = CreateObject((Int16) (Double) subject.Value);
break;
case TypeCode.UInt16:
result = CreateObject((UInt16) (Double) subject.Value);
break;
case TypeCode.Int64:
result = CreateObject((Int64) (Double) subject.Value);
break;
case TypeCode.UInt64:
result = CreateObject((UInt64) (Double) subject.Value);
break;
case TypeCode.Single:
result = CreateObject((Single) (Double) subject.Value);
break;
}
}
}
// (!useImplicit)
if (result == null)
{
if (target is StringPType)
result = String.CreatePValue(subject.Value.ToString());
else if (target is RealPType)
result = Real.CreatePValue((double) subject.Value);
else if (target is BoolPType)
result = Bool.CreatePValue(((double) subject.Value) != 0.0);
else if (target is ObjectPType)
{
switch (Type.GetTypeCode(((ObjectPType) target).ClrType))
{
case TypeCode.Double:
result = CreateObject((Double) subject.Value);
break;
case TypeCode.Decimal:
result = CreateObject((Decimal) subject.Value);
break;
}
}
}
return result != null;
}
protected override bool InternalConvertFrom(
StackContext sctx,
PValue subject,
bool useExplicit,
out PValue result)
{
result = null;
var subjectType = subject.Type;
if (subjectType is StringPType)
{
double value;
if (double.TryParse(subject.Value as string, out value))
result = value; //Conversion succeeded
else if (useExplicit)
return false; //Conversion required, provoke error
else
result = 0; //Conversion not required, return default value
}
else if (subjectType is ObjectPType)
{
if (useExplicit)
switch (Type.GetTypeCode((subjectType as ObjectPType).ClrType))
{
case TypeCode.Decimal:
case TypeCode.Char:
result = (double) subject.Value;
break;
case TypeCode.Boolean:
result = ((bool) subject.Value) ? 1.0 : 0.0;
break;
}
if (result != null)
{
//(!useExplicit || useExplicit)
switch (Type.GetTypeCode((subjectType as ObjectPType).ClrType))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
result = (double) subject.Value;
break;
}
}
}
return result != null;
}
private static bool _tryConvertToReal(StackContext sctx, PValue operand, out double value)
{
return _tryConvertToReal(sctx, operand, out value, true);
}
private static bool _tryConvertToReal(
StackContext sctx, PValue operand, out double value, bool allowNull)
{
value = -133.7; //should never surface as value is only used if the method returns true
switch (operand.Type.ToBuiltIn())
{
case BuiltIn.Int:
case BuiltIn.Real:
value = Convert.ToDouble(operand.Value);
return true;
/*
case BuiltIn.String:
string rawRight = operand.Value as string;
if (!double.TryParse(rawRight, out value))
value = 0.0;
return true; //*/
case BuiltIn.Object:
PValue pvRight;
if (operand.TryConvertTo(sctx, Real, out pvRight))
{
value = (int) pvRight.Value;
return true;
}
break;
case BuiltIn.Null:
value = 0.0;
return allowNull;
default:
break;
}
return false;
}
public override bool Addition(
StackContext sctx, PValue leftOperand, PValue rightOperand, out PValue result)
{
result = null;
double left;
double right;
if (_tryConvertToReal(sctx, leftOperand, out left) &&
_tryConvertToReal(sctx, rightOperand, out right))
result = left + right;
return result != null;
}
public override bool Subtraction(
StackContext sctx, PValue leftOperand, PValue rightOperand, out PValue result)
{
result = null;
double left;
double right;
if (_tryConvertToReal(sctx, leftOperand, out left) &&
_tryConvertToReal(sctx, rightOperand, out right))
result = left - right;
return result != null;
}
public override bool Multiply(
StackContext sctx, PValue leftOperand, PValue rightOperand, out PValue result)
{
result = null;
double left;
double right;
if (_tryConvertToReal(sctx, leftOperand, out left) &&
_tryConvertToReal(sctx, rightOperand, out right))
result = left*right;
return result != null;
}
public override bool Division(
StackContext sctx, PValue leftOperand, PValue rightOperand, out PValue result)
{
result = null;
double left;
double right;
if (_tryConvertToReal(sctx, leftOperand, out left) &&
_tryConvertToReal(sctx, rightOperand, out right))
result = left/right;
return result != null;
}
public override bool Modulus(
StackContext sctx, PValue leftOperand, PValue rightOperand, out PValue result)
{
result = null;
double left;
double right;
if (_tryConvertToReal(sctx, leftOperand, out left) &&
_tryConvertToReal(sctx, rightOperand, out right))
result = left%right;
return result != null;
}
public override bool Equality(
StackContext sctx, PValue leftOperand, PValue rightOperand, out PValue result)
{
result = null;
double left;
double right;
if (_tryConvertToReal(sctx, leftOperand, out left, false) &&
_tryConvertToReal(sctx, rightOperand, out right, false))
result = left == right;
return result != null;
}
public override bool Inequality(
StackContext sctx, PValue leftOperand, PValue rightOperand, out PValue result)
{
result = null;
double left;
double right;
if (_tryConvertToReal(sctx, leftOperand, out left, false) &&
_tryConvertToReal(sctx, rightOperand, out right, false))
result = left != right;
return result != null;
}
public override bool GreaterThan(
StackContext sctx, PValue leftOperand, PValue rightOperand, out PValue result)
{
result = null;
double left;
double right;
if (_tryConvertToReal(sctx, leftOperand, out left) &&
_tryConvertToReal(sctx, rightOperand, out right))
result = left > right;
return result != null;
}
public override bool GreaterThanOrEqual(
StackContext sctx,
PValue leftOperand,
PValue rightOperand,
out PValue result)
{
result = null;
double left;
double right;
if (_tryConvertToReal(sctx, leftOperand, out left) &&
_tryConvertToReal(sctx, rightOperand, out right))
result = left >= right;
return result != null;
}
public override bool LessThan(
StackContext sctx, PValue leftOperand, PValue rightOperand, out PValue result)
{
result = null;
double left;
double right;
if (_tryConvertToReal(sctx, leftOperand, out left) &&
_tryConvertToReal(sctx, rightOperand, out right))
result = left < right;
return result != null;
}
public override bool LessThanOrEqual(
StackContext sctx,
PValue leftOperand,
PValue rightOperand,
out PValue result)
{
result = null;
double left;
double right;
if (_tryConvertToReal(sctx, leftOperand, out left) &&
_tryConvertToReal(sctx, rightOperand, out right))
result = left <= right;
return result != null;
}
public override bool UnaryNegation(StackContext sctx, PValue operand, out PValue result)
{
result = null;
double op;
if (_tryConvertToReal(sctx, operand, out op))
result = -op;
return result != null;
}
public override bool Increment(StackContext sctx, PValue operand, out PValue result)
{
result = null;
double op;
if (_tryConvertToReal(sctx, operand, out op))
result = op + 1.0;
return result != null;
}
public override bool Decrement(StackContext sctx, PValue operand, out PValue result)
{
result = null;
double op;
if (_tryConvertToReal(sctx, operand, out op))
result = op - 1.0;
return result != null;
}
protected override bool InternalIsEqual(PType otherType)
{
return otherType is RealPType;
}
private const int _code = -2035946599;
public override int GetHashCode()
{
return _code;
}
#endregion
public const string Literal = "Real";
public override string ToString()
{
return Literal;
}
#region ICilCompilerAware Members
/// <summary>
/// Asses qualification and preferences for a certain instruction.
/// </summary>
/// <param name = "ins">The instruction that is about to be compiled.</param>
/// <returns>A set of <see cref = "CompilationFlags" />.</returns>
CompilationFlags ICilCompilerAware.CheckQualification(Instruction ins)
{
return CompilationFlags.PrefersCustomImplementation;
}
/// <summary>
/// Provides a custom compiler routine for emitting CIL byte code for a specific instruction.
/// </summary>
/// <param name = "state">The compiler state.</param>
/// <param name = "ins">The instruction to compile.</param>
void ICilCompilerAware.ImplementInCil(CompilerState state, Instruction ins)
{
state.EmitCall(Compiler.Cil.Compiler.GetRealPType);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq.Expressions;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using Signum.Utilities.ExpressionTrees;
namespace Signum.Utilities.Reflection
{
public static class ReflectionTools
{
public static bool? IsNullable(this FieldInfo fi, int position = 0)
{
var result = fi.GetCustomAttribute<NullableAttribute>();
if (result != null)
return result.GetNullable(position);
if (fi.FieldType.IsValueType)
return null;
return fi.DeclaringType!.IsNullableFromContext(position);
}
public static bool? IsNullable(this PropertyInfo pi, int position = 0)
{
var result = pi.GetCustomAttribute<NullableAttribute>();
if (result != null)
return result.GetNullable(position);
if (pi.PropertyType.IsValueType)
return null;
return pi.DeclaringType!.IsNullableFromContext();
}
public static bool? IsNullableFromContext(this Type ti, int position = 0)
{
var result = ti.GetCustomAttribute<NullableContextAttribute>();
if (result != null)
return result.GetNullable(position);
return ti.DeclaringType?.IsNullableFromContext(position);
}
public static bool? GetNullable(this NullableContextAttribute attr, int position = 0)
{
if (position > 0 && attr.NullableFlags.Length == 1)
position = 0;
var first = attr.NullableFlags[position];
return first == 1 ? (bool?)false :
first == 2 ? (bool?)true :
null;
}
public static bool? GetNullable(this NullableAttribute attr, int position = 0)
{
if (position > 0 && attr.NullableFlags.Length == 1)
position = 0;
var first = attr.NullableFlags[position];
return first == 1 ? (bool?)false :
first == 2 ? (bool?)true :
null;
}
public static bool FieldEquals(FieldInfo f1, FieldInfo f2)
{
return MemeberEquals(f1, f2);
}
public static bool PropertyEquals(PropertyInfo p1, PropertyInfo p2)
{
return MemeberEquals(p1, p2);
}
public static bool MethodEqual(MethodInfo m1, MethodInfo m2)
{
return MemeberEquals(m1, m2);
}
public static bool MemeberEquals(MemberInfo m1, MemberInfo m2)
{
if (m1 == m2)
return true;
if (m1.DeclaringType != m2.DeclaringType)
return false;
// Methods on arrays do not have metadata tokens but their ReflectedType
// always equals their DeclaringType
if (m1.DeclaringType != null && m1.DeclaringType.IsArray)
return false;
if (m1.MetadataToken != m2.MetadataToken || m1.Module != m2.Module)
return false;
if (m1 is MethodInfo lhsMethod)
{
if (lhsMethod.IsGenericMethod)
{
MethodInfo rhsMethod = (MethodInfo)m2;
Type[] lhsGenArgs = lhsMethod.GetGenericArguments();
Type[] rhsGenArgs = rhsMethod.GetGenericArguments();
for (int i = 0; i < rhsGenArgs.Length; i++)
{
if (lhsGenArgs[i] != rhsGenArgs[i])
return false;
}
}
}
return true;
}
public static PropertyInfo GetPropertyInfo<R>(Expression<Func<R>> property)
{
return BasePropertyInfo(property);
}
public static PropertyInfo GetPropertyInfo<T, R>(Expression<Func<T, R>> property)
{
return BasePropertyInfo(property);
}
public static PropertyInfo BasePropertyInfo(LambdaExpression property)
{
if (property == null)
throw new ArgumentNullException("property");
Expression body = property.Body;
if (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
if (!(body is MemberExpression ex))
throw new ArgumentException("The lambda 'property' should be an expression accessing a property");
if (!(ex.Member is PropertyInfo pi))
throw new ArgumentException("The lambda 'property' should be an expression accessing a property");
return pi;
}
public static ConstructorInfo GetConstuctorInfo<R>(Expression<Func<R>> constuctor)
{
return BaseConstuctorInfo(constuctor);
}
public static ConstructorInfo BaseConstuctorInfo(LambdaExpression constuctor)
{
if (constuctor == null)
throw new ArgumentNullException("constuctor");
Expression body = constuctor.Body;
if (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
if (!(body is NewExpression ex))
throw new ArgumentException("The lambda 'constuctor' should be an expression constructing an object");
return ex.Constructor;
}
public static FieldInfo GetFieldInfo<R>(Expression<Func<R>> field)
{
return BaseFieldInfo(field);
}
public static FieldInfo GetFieldInfo<T, R>(Expression<Func<T, R>> field)
{
return BaseFieldInfo(field);
}
public static FieldInfo BaseFieldInfo(LambdaExpression field)
{
if (field == null)
throw new ArgumentNullException("field");
Expression body = field.Body;
if (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
if (!(body is MemberExpression ex))
throw new ArgumentException("The lambda 'field' should be an expression accessing a field");
if (!(ex.Member is FieldInfo fi))
throw new ArgumentException("The lambda 'field' should be an expression accessing a field");
return fi;
}
public static MemberInfo GetMemberInfo<R>(Expression<Func<R>> member)
{
return BaseMemberInfo(member);
}
public static MemberInfo GetMemberInfo<T, R>(Expression<Func<T, R>> member)
{
return BaseMemberInfo(member);
}
public static MemberInfo BaseMemberInfo(LambdaExpression member)
{
if (member == null)
throw new ArgumentNullException("member");
Expression body = member.Body;
if (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
if (!(body is MemberExpression me))
throw new ArgumentException("The lambda 'member' should be an expression accessing a member");
return me.Member;
}
public static MethodInfo GetMethodInfo(Expression<Action> method)
{
return BaseMethodInfo(method);
}
public static MethodInfo GetMethodInfo<T>(Expression<Action<T>> method)
{
return BaseMethodInfo(method);
}
public static MethodInfo GetMethodInfo<R>(Expression<Func<R>> method)
{
return BaseMethodInfo(method);
}
public static MethodInfo GetMethodInfo<T, R>(Expression<Func<T, R>> method)
{
return BaseMethodInfo(method);
}
public static MethodInfo BaseMethodInfo(LambdaExpression method)
{
if (method == null)
throw new ArgumentNullException("method");
Expression body = method.Body;
if (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
if (!(body is MethodCallExpression ex))
throw new ArgumentException("The lambda 'method' should be an expression calling a method");
return ex.Method;
}
public static ConstructorInfo GetGenericConstructorDefinition(this ConstructorInfo ci)
{
return ci.DeclaringType!.GetGenericTypeDefinition().GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).SingleEx(a => a.MetadataToken == ci.MetadataToken);
}
public static ConstructorInfo MakeGenericConstructor(this ConstructorInfo ci, params Type[] types)
{
return ci.DeclaringType!.MakeGenericType(types).GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).SingleEx(a => a.MetadataToken == ci.MetadataToken);
}
public static Type GetReceiverType<T, R>(Expression<Func<T, R>> lambda)
{
Expression body = lambda.Body;
if (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
return ((MemberExpression)body).Expression.Type;
}
public static Func<T, P>? CreateGetter<T, P>(MemberInfo m)
{
if ((m as PropertyInfo)?.Let(a => !a.CanRead) ?? false)
return null;
ParameterExpression p = Expression.Parameter(typeof(T), "p");
var exp = Expression.Lambda(typeof(Func<T, P>), Expression.MakeMemberAccess(p, m), p);
return (Func<T, P>)exp.Compile();
}
public static Func<T, object?>? CreateGetter<T>(MemberInfo m)
{
using (HeavyProfiler.LogNoStackTrace("CreateGetter"))
{
if ((m as PropertyInfo)?.Let(a => !a.CanRead) ?? false)
return null;
ParameterExpression p = Expression.Parameter(typeof(T), "p");
Type lambdaType = typeof(Func<,>).MakeGenericType(typeof(T), typeof(object));
var exp = Expression.Lambda(lambdaType, Expression.Convert(Expression.MakeMemberAccess(p, m), typeof(object)), p);
return (Func<T, object?>)exp.Compile();
}
}
public static Func<object, object?>? CreateGetterUntyped(Type type, MemberInfo m)
{
using (HeavyProfiler.LogNoStackTrace("CreateGetterUntyped"))
{
if ((m as PropertyInfo)?.Let(a => !a.CanRead) ?? false)
return null;
ParameterExpression p = Expression.Parameter(typeof(object), "p");
Type lambdaType = typeof(Func<,>).MakeGenericType(typeof(object), typeof(object));
var exp = Expression.Lambda(lambdaType, Expression.Convert(Expression.MakeMemberAccess(Expression.Convert(p, type), m), typeof(object)), p);
return (Func<object, object?>)exp.Compile();
}
}
public static Action<T, P>? CreateSetter<T, P>(MemberInfo m)
{
using (HeavyProfiler.LogNoStackTrace("CreateSetter"))
{
if ((m as PropertyInfo)?.Let(a => !a.CanWrite) ?? false)
return null;
ParameterExpression t = Expression.Parameter(typeof(T), "t");
ParameterExpression p = Expression.Parameter(typeof(P), "p");
var exp = Expression.Lambda(typeof(Action<T, P>),
Expression.Assign(Expression.MakeMemberAccess(t, m), p), t, p);
return (Action<T, P>)exp.Compile();
}
}
public static Action<T, object?>? CreateSetter<T>(MemberInfo m)
{
using (HeavyProfiler.LogNoStackTrace("CreateSetter"))
{
if ((m as PropertyInfo)?.Let(a => !a.CanWrite) ?? false)
return null;
ParameterExpression t = Expression.Parameter(typeof(T), "t");
ParameterExpression p = Expression.Parameter(typeof(object), "p");
var exp = Expression.Lambda(typeof(Action<T, object>),
Expression.Assign(Expression.MakeMemberAccess(t, m), Expression.Convert(p, m.ReturningType())), t, p);
return (Action<T, object?>)exp.Compile();
}
}
public static Action<object, object?>? CreateSetterUntyped(Type type, MemberInfo m)
{
using (HeavyProfiler.LogNoStackTrace("CreateSetterUntyped"))
{
if ((m as PropertyInfo)?.Let(a => !a.CanWrite) ?? false)
return null;
ParameterExpression t = Expression.Parameter(typeof(object), "t");
ParameterExpression p = Expression.Parameter(typeof(object), "p");
var exp = Expression.Lambda(typeof(Action<object, object>),
Expression.Assign(Expression.MakeMemberAccess(Expression.Convert(t, type), m), Expression.Convert(p, m.ReturningType())), t, p);
return (Action<object, object?>)exp.Compile();
}
}
public static bool IsNumber(Type type)
{
type = type.UnNullify();
if (type.IsEnum)
return false;
switch (Type.GetTypeCode(type))
{
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64: return true;
}
return false;
}
public static bool IsIntegerNumber(Type type)
{
type = type.UnNullify();
if (type.IsEnum)
return false;
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64: return true;
}
return false;
}
public static bool IsDecimalNumber(Type type)
{
type = type.UnNullify();
if (type.IsEnum)
return false;
switch (Type.GetTypeCode(type))
{
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
}
return false;
}
public static bool IsPercentage(string formatString, CultureInfo culture)
{
return formatString.HasText() && formatString.StartsWith("p", StringComparison.InvariantCultureIgnoreCase);
}
public static object? ParsePercentage(string value, Type targetType, CultureInfo culture)
{
value = value.Trim(culture.NumberFormat.PercentSymbol.ToCharArray());
if (string.IsNullOrEmpty(value))
return null;
switch (Type.GetTypeCode(targetType.UnNullify()))
{
case TypeCode.Single: return Single.Parse(value, culture) / 100.0f;
case TypeCode.Double: return Double.Parse(value, culture) / 100.0;
case TypeCode.Decimal: return Decimal.Parse(value, culture) / 100M;
case TypeCode.Byte: return (Byte)(Byte.Parse(value, culture) / 100);
case TypeCode.Int16: return (Int16)(Int16.Parse(value, culture) / 100);
case TypeCode.Int32: return (Int32)(Int32.Parse(value, culture) / 100);
case TypeCode.Int64: return (Int64)(Int64.Parse(value, culture) / 100);
case TypeCode.UInt16: return (UInt16)(UInt16.Parse(value, culture) / 100);
case TypeCode.UInt32: return (UInt32)(UInt32.Parse(value, culture) / 100);
case TypeCode.UInt64: return (UInt64)(UInt64.Parse(value, culture) / 100);
default:
throw new InvalidOperationException("targetType is not a number");
}
}
public static T Parse<T>(string value)
{
if (typeof(T) == typeof(string))
return (T)(object)value;
if (value == null || value == "")
return (T)(object?)null!;
Type utype = typeof(T).UnNullify();
if (utype.IsEnum)
return (T)Enum.Parse(utype, (string)value);
else if (utype == typeof(Guid))
return (T)(object)Guid.Parse(value);
else
return (T)Convert.ChangeType(value, utype)!;
}
public static object? Parse(string value, Type type)
{
if (type == typeof(string))
return (object)value;
if (value == null || value == "" || value == " ")
return (object?)null;
Type utype = type.UnNullify();
if (utype.IsEnum)
return Enum.Parse(utype, (string)value);
if (utype == typeof(Guid))
return Guid.Parse(value);
if (CustomParsers.TryGetValue(utype, out var func))
return func(value); //Delay reference
return Convert.ChangeType(value, utype);
}
public static Dictionary<Type, Func<string, object>> CustomParsers = new Dictionary<Type, Func<string, object>>
{
//{ typeof(SqlHierarchyId), str => SqlHierarchyId.Parse(str) },
//{ typeof(SqlGeography), str => SqlGeography.Parse(str) },
//{ typeof(SqlGeometry), str => SqlGeometry.Parse(str) },
};
public static T Parse<T>(string value, CultureInfo culture)
{
if (typeof(T) == typeof(string))
return (T)(object)value;
if (value == null || value == "")
return (T)(object?)null!;
Type utype = typeof(T).UnNullify();
if (utype.IsEnum)
return (T)Enum.Parse(utype, (string)value);
else if (utype == typeof(Guid))
return (T)(object)Guid.Parse(value);
else
return (T)Convert.ChangeType(value, utype, culture)!;
}
public static object? Parse(string value, Type type, CultureInfo culture)
{
if (type == typeof(string))
return value;
if (value == null || value == "")
return null;
Type utype = type.UnNullify();
if (utype.IsEnum)
return Enum.Parse(utype, (string)value);
else if (utype == typeof(Guid))
return Guid.Parse(value);
else
return Convert.ChangeType(value, utype, culture);
}
public static bool TryParse<T>(string value, out T result)
{
if (TryParse(value, typeof(T), CultureInfo.CurrentCulture, out object? objResult))
{
result = (T)objResult!;
return true;
}
else
{
result = default(T)!;
return false;
}
}
public static bool TryParse<T>(string value, CultureInfo ci, out T result)
{
if (TryParse(value, typeof(T), ci, out object? objResult))
{
result = (T)objResult!;
return true;
}
else
{
result = default(T)!;
return false;
}
}
public static bool TryParse(string? value, Type type, out object? result)
{
return TryParse(value, type, CultureInfo.CurrentCulture, out result);
}
public static bool TryParse(string? value, Type type, CultureInfo ci, out object? result)
{
if (type == typeof(string))
{
result = value;
return true;
}
result = null;
if (!value.HasText())
{
if (Nullable.GetUnderlyingType(type) == null && type.IsValueType)
{
return false;
}
return true;
}
Type utype = type.UnNullify();
if (utype.IsEnum)
{
if (EnumExtensions.TryParse(value, utype, true, out Enum _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(bool))
{
if (bool.TryParse(value, out bool _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(char))
{
if (char.TryParse(value, out char _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(SByte))
{
if (SByte.TryParse(value, NumberStyles.Integer, ci, out sbyte _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(byte))
{
if (byte.TryParse(value, NumberStyles.Integer, ci, out byte _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(Int16))
{
if (Int16.TryParse(value, NumberStyles.Integer, ci, out short _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(UInt16))
{
if (UInt16.TryParse(value, NumberStyles.Integer, ci, out ushort _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(Int32))
{
if (Int32.TryParse(value, NumberStyles.Integer, ci, out int _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(UInt32))
{
if (UInt32.TryParse(value, NumberStyles.Integer, ci, out uint _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(Int64))
{
if (Int64.TryParse(value, NumberStyles.Integer, ci, out long _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(UInt64))
{
if (UInt64.TryParse(value, NumberStyles.Integer, ci, out ulong _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(float))
{
if (float.TryParse(value, NumberStyles.Number, ci, out float _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(double))
{
if (double.TryParse(value, NumberStyles.Number, ci, out double _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(decimal))
{
if (decimal.TryParse(value, NumberStyles.Number, ci, out decimal _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(DateTime))
{
if (DateTime.TryParse(value, ci, DateTimeStyles.None, out DateTime _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(Guid))
{
if (Guid.TryParse(value, out Guid _result))
{
result = _result;
return true;
}
else return false;
}
else if (utype == typeof(object))
{
result = value;
return true;
}
else
{
TypeConverter converter = TypeDescriptor.GetConverter(utype);
if (converter.CanConvertFrom(typeof(string)))
{
try
{
result = converter.ConvertFromString(null, ci, value);
return true;
}
catch (Exception)
{
return false;
}
}
else return false;
}
}
public static T ChangeType<T>(object? value)
{
if (value == null)
return (T)(object?)null!;
if (value.GetType() == typeof(T))
return (T)value;
else
{
Type utype = typeof(T).UnNullify();
if (utype.IsEnum)
{
if (value is string)
return (T)Enum.Parse(utype, (string)value);
else
return (T)Enum.ToObject(utype, value);
}
else if (utype == typeof(Guid) && value is string)
return (T)(object)Guid.Parse((string)value);
else
return (T)Convert.ChangeType(value, utype)!;
}
}
public static object? ChangeType(object? value, Type type)
{
if (value == null)
return null;
if (type.IsAssignableFrom(value.GetType()))
return value;
else
{
Type utype = type.UnNullify();
if (utype.IsEnum)
{
if (value is string)
return Enum.Parse(utype, (string)value);
else
return Enum.ToObject(utype, value);
}
else if (utype == typeof(Guid) && value is string)
return Guid.Parse((string)value);
else
{
var conv = TypeDescriptor.GetConverter(type);
if(conv != null && conv.CanConvertFrom(value.GetType()))
return conv.ConvertFrom(value);
conv = TypeDescriptor.GetConverter(value.GetType());
if (conv != null && conv.CanConvertTo(type))
return conv.ConvertTo(value, type);
if(type != typeof(string) && value is IEnumerable && typeof(IEnumerable).IsAssignableFrom(type))
{
var colType = type.IsInstantiationOf(typeof(IEnumerable<>)) ? typeof(List<>).MakeGenericType(type.GetGenericArguments()) : type;
IList col = (IList)Activator.CreateInstance(colType)!;
foreach (var item in (IEnumerable)value)
{
col.Add(item);
}
return col;
}
if (value is IConvertible c)
return Convert.ChangeType(c, utype);
throw new InvalidOperationException($"Unable to convert '{value}' (of type {value.GetType().TypeName()}) to type {utype.TypeName()}");
}
}
}
public static bool IsStatic(this PropertyInfo pi)
{
return (pi.CanRead && pi.GetGetMethod()!.IsStatic) ||
(pi.CanWrite && pi.GetSetMethod()!.IsStatic);
}
}
}
| |
/*
Copyright 2018 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Threading.Tasks;
using ArcGIS.Core.Data;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Framework.Threading.Tasks;
namespace SDKExamples
{
/// <summary>
/// Illustrates how to create a Row in a Table.
/// </summary>
///
/// <remarks>
/// <para>
/// While it is true classes that are derived from the <see cref="ArcGIS.Core.CoreObjectsBase"/> super class
/// consumes native resources (e.g., <see cref="ArcGIS.Core.Data.Geodatabase"/> or <see cref="ArcGIS.Core.Data.FeatureClass"/>),
/// you can rest assured that the garbage collector will properly dispose of the unmanaged resources during
/// finalization. However, there are certain workflows that require a <b>deterministic</b> finalization of the
/// <see cref="ArcGIS.Core.Data.Geodatabase"/>. Consider the case of a file geodatabase that needs to be deleted
/// on the fly at a particular moment. Because of the <b>indeterministic</b> nature of garbage collection, we can't
/// count on the garbage collector to dispose of the Geodatabase object, thereby removing the <b>lock(s)</b> at the
/// moment we want. To ensure a deterministic finalization of important native resources such as a
/// <see cref="ArcGIS.Core.Data.Geodatabase"/> or <see cref="ArcGIS.Core.Data.FeatureClass"/>, you should declare
/// and instantiate said objects in a <b>using</b> statement. Alternatively, you can achieve the same result by
/// putting the object inside a try block and then calling Dispose() in a finally block.
/// </para>
/// <para>
/// In general, you should always call Dispose() on the following types of objects:
/// </para>
/// <para>
/// - Those that are derived from <see cref="ArcGIS.Core.Data.Datastore"/> (e.g., <see cref="ArcGIS.Core.Data.Geodatabase"/>).
/// </para>
/// <para>
/// - Those that are derived from <see cref="ArcGIS.Core.Data.Dataset"/> (e.g., <see cref="ArcGIS.Core.Data.Table"/>).
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.RowCursor"/> and <see cref="ArcGIS.Core.Data.RowBuffer"/>.
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.Row"/> and <see cref="ArcGIS.Core.Data.Feature"/>.
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.Selection"/>.
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.VersionManager"/> and <see cref="ArcGIS.Core.Data.Version"/>.
/// </para>
/// </remarks>
public class TableCreateRow
{
/// <summary>
/// In order to illustrate that Geodatabase calls have to be made on the MCT
/// </summary>
/// <returns></returns>
public async Task MainMethodCode()
{
await QueuedTask.Run(async () =>
{
await EnterpriseGeodabaseWorkFlow();
await FileGeodatabaseWorkFlow();
});
}
private static async Task EnterpriseGeodabaseWorkFlow()
{
// Opening a Non-Versioned SQL Server instance.
DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
{
AuthenticationMode = AuthenticationMode.DBMS,
// Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance.
Instance = @"testMachine\testInstance",
// Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database.
Database = "LocalGovernment",
// Provided that a login called gdb has been created and corresponding schema has been created with the required permissions.
User = "gdb",
Password = "password",
Version = "dbo.DEFAULT"
};
using (Geodatabase geodatabase = new Geodatabase(connectionProperties))
using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
{
EditOperation editOperation = new EditOperation();
editOperation.Callback(context =>
{
RowBuffer rowBuffer = null;
Row row = null;
try
{
TableDefinition tableDefinition = enterpriseTable.GetDefinition();
int assetNameIndex = tableDefinition.FindField("ASSETNA");
rowBuffer = enterpriseTable.CreateRowBuffer();
// Either the field index or the field name can be used in the indexer.
rowBuffer[assetNameIndex] = "wMain";
rowBuffer["COST"] = 700;
rowBuffer["ACTION"] = "Open Cut";
// subtype value for "Abandon".
rowBuffer[tableDefinition.GetSubtypeField()] = 3;
row = enterpriseTable.CreateRow(rowBuffer);
//To Indicate that the attribute table has to be updated
context.Invalidate(row);
long objectID = row.GetObjectID();
// Do some other processing with the row.
}
catch (GeodatabaseException exObj)
{
Console.WriteLine(exObj);
}
finally
{
if (rowBuffer != null)
rowBuffer.Dispose();
if (row != null)
row.Dispose();
}
}, enterpriseTable);
bool editResult = editOperation.Execute();
// If the table is non-versioned this is a no-op. If it is versioned, we need the Save to be done for the edits to be persisted.
bool saveResult = await Project.Current.SaveEditsAsync();
}
}
// Illustrates creating a row in a File GDB.
private static async Task FileGeodatabaseWorkFlow()
{
using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb"))))
using (Table table = fileGeodatabase.OpenDataset<Table>("EmployeeInfo"))
{
EditOperation editOperation = new EditOperation();
editOperation.Callback(context =>
{
RowBuffer rowBuffer = null;
Row row = null;
try
{
TableDefinition tableDefinition = table.GetDefinition();
int firstNameIndex = tableDefinition.FindField("FIRSTNAME");
rowBuffer = table.CreateRowBuffer();
// Either the field index or the field name can be used in the indexer.
rowBuffer[firstNameIndex] = "John";
rowBuffer["LASTNAME"] = "Doe";
rowBuffer["COSTCTR"] = 4470;
rowBuffer["COSTCTRN"] = "Information Technology";
rowBuffer["EXTENSION"] = 12345;
rowBuffer["EMAIL"] = "johndoe@naperville.com";
rowBuffer["BUILDING"] = "MC";
rowBuffer["FLOOR"] = 1;
rowBuffer["WING"] = "E";
rowBuffer["OFFICE"] = 58;
rowBuffer["LOCATION"] = "MC1E58";
row = table.CreateRow(rowBuffer);
//To Indicate that the attribute table has to be updated
context.Invalidate(row);
// Do some other processing with the row.
}
catch (GeodatabaseException exObj)
{
Console.WriteLine(exObj);
}
finally
{
if (rowBuffer != null)
rowBuffer.Dispose();
if (row != null)
row.Dispose();
}
}, table);
bool editResult = editOperation.Execute();
// If the table is non-versioned this is a no-op. If it is versioned, we need the Save to be done for the edits to be persisted.
bool saveResult = await Project.Current.SaveEditsAsync();
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for VirtualNetworkGatewayConnectionsOperations.
/// </summary>
public static partial class VirtualNetworkGatewayConnectionsOperationsExtensions
{
/// <summary>
/// Creates or updates a virtual network gateway connection in the specified
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network gateway
/// connection operation.
/// </param>
public static VirtualNetworkGatewayConnection CreateOrUpdate(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a virtual network gateway connection in the specified
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network gateway
/// connection operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetworkGatewayConnection> CreateOrUpdateAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the specified virtual network gateway connection by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
public static VirtualNetworkGatewayConnection Get(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName)
{
return operations.GetAsync(resourceGroupName, virtualNetworkGatewayConnectionName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified virtual network gateway connection by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetworkGatewayConnection> GetAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified virtual network Gateway connection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
public static void Delete(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName)
{
operations.DeleteAsync(resourceGroupName, virtualNetworkGatewayConnectionName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified virtual network Gateway connection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual
/// network gateway connection shared key for passed virtual network gateway
/// connection in the specified resource group through Network resource
/// provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway connection
/// Shared key operation throughNetwork resource provider.
/// </param>
public static ConnectionSharedKey SetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters)
{
return operations.SetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual
/// network gateway connection shared key for passed virtual network gateway
/// connection in the specified resource group through Network resource
/// provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway connection
/// Shared key operation throughNetwork resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ConnectionSharedKey> SetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.SetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves
/// information about the specified virtual network gateway connection shared
/// key through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection shared key name.
/// </param>
public static ConnectionSharedKey GetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName)
{
return operations.GetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName).GetAwaiter().GetResult();
}
/// <summary>
/// The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves
/// information about the specified virtual network gateway connection shared
/// key through Network resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection shared key name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ConnectionSharedKey> GetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List VirtualNetworkGatewayConnections operation retrieves all the
/// virtual network gateways connections created.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<VirtualNetworkGatewayConnection> List(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// The List VirtualNetworkGatewayConnections operation retrieves all the
/// virtual network gateways connections created.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualNetworkGatewayConnection>> ListAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the
/// virtual network gateway connection shared key for passed virtual network
/// gateway connection in the specified resource group through Network resource
/// provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the begin reset virtual network gateway connection
/// shared key operation through network resource provider.
/// </param>
public static ConnectionResetSharedKey ResetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters)
{
return operations.ResetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the
/// virtual network gateway connection shared key for passed virtual network
/// gateway connection in the specified resource group through Network resource
/// provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the begin reset virtual network gateway connection
/// shared key operation through network resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ConnectionResetSharedKey> ResetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ResetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a virtual network gateway connection in the specified
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network gateway
/// connection operation.
/// </param>
public static VirtualNetworkGatewayConnection BeginCreateOrUpdate(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a virtual network gateway connection in the specified
/// resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update virtual network gateway
/// connection operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualNetworkGatewayConnection> BeginCreateOrUpdateAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified virtual network Gateway connection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
public static void BeginDelete(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName)
{
operations.BeginDeleteAsync(resourceGroupName, virtualNetworkGatewayConnectionName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified virtual network Gateway connection.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The name of the virtual network gateway connection.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual
/// network gateway connection shared key for passed virtual network gateway
/// connection in the specified resource group through Network resource
/// provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway connection
/// Shared key operation throughNetwork resource provider.
/// </param>
public static ConnectionSharedKey BeginSetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters)
{
return operations.BeginSetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual
/// network gateway connection shared key for passed virtual network gateway
/// connection in the specified resource group through Network resource
/// provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Set Virtual Network Gateway connection
/// Shared key operation throughNetwork resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ConnectionSharedKey> BeginSetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginSetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the
/// virtual network gateway connection shared key for passed virtual network
/// gateway connection in the specified resource group through Network resource
/// provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the begin reset virtual network gateway connection
/// shared key operation through network resource provider.
/// </param>
public static ConnectionResetSharedKey BeginResetSharedKey(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters)
{
return operations.BeginResetSharedKeyAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the
/// virtual network gateway connection shared key for passed virtual network
/// gateway connection in the specified resource group through Network resource
/// provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayConnectionName'>
/// The virtual network gateway connection reset shared key Name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the begin reset virtual network gateway connection
/// shared key operation through network resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ConnectionResetSharedKey> BeginResetSharedKeyAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginResetSharedKeyWithHttpMessagesAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The List VirtualNetworkGatewayConnections operation retrieves all the
/// virtual network gateways connections created.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualNetworkGatewayConnection> ListNext(this IVirtualNetworkGatewayConnectionsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// The List VirtualNetworkGatewayConnections operation retrieves all the
/// virtual network gateways connections created.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualNetworkGatewayConnection>> ListNextAsync(this IVirtualNetworkGatewayConnectionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// 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.Linq;
using JetBrains.Annotations;
using osu.Framework.Extensions;
using osu.Framework.Graphics.Sprites;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A container which tabulates <see cref="Drawable"/>s.
/// </summary>
public class TableContainer : CompositeDrawable
{
private readonly GridContainer grid;
public TableContainer()
{
InternalChild = grid = new GridContainer { RelativeSizeAxes = Axes.Both };
}
private Drawable[,] content;
/// <summary>
/// The content of this <see cref="TableContainer"/>, arranged in a 2D rectangular array.
/// <para>
/// Null elements are allowed to represent blank rows/cells.
/// </para>
/// </summary>
[CanBeNull]
public Drawable[,] Content
{
get => content;
set
{
if (content == value)
return;
content = value;
updateContent();
}
}
private TableColumn[] columns = Array.Empty<TableColumn>();
/// <summary>
/// Describes the columns of this <see cref="TableContainer"/>.
/// Each index of this array applies to the respective column index inside <see cref="Content"/>.
/// </summary>
public TableColumn[] Columns
{
[NotNull]
get => columns;
[CanBeNull]
set
{
value ??= Array.Empty<TableColumn>();
if (columns == value)
return;
columns = value;
updateContent();
}
}
private Dimension rowSize = new Dimension();
/// <summary>
/// Explicit dimensions for rows. The dimension is applied to every row of this <see cref="TableContainer"/>
/// </summary>
public Dimension RowSize
{
[NotNull]
get => rowSize;
[CanBeNull]
set
{
value ??= new Dimension();
if (rowSize == value)
return;
rowSize = value;
updateContent();
}
}
private bool showHeaders = true;
/// <summary>
/// Whether to display a row with column headers at the top of the table.
/// </summary>
public bool ShowHeaders
{
get => showHeaders;
set
{
if (showHeaders == value)
return;
showHeaders = value;
updateContent();
}
}
public override Axes RelativeSizeAxes
{
get => base.RelativeSizeAxes;
set
{
base.RelativeSizeAxes = value;
updateGridSize();
}
}
/// <summary>
/// Controls which <see cref="Axes"/> are automatically sized w.r.t. <see cref="CompositeDrawable.InternalChildren"/>.
/// Children's <see cref="Drawable.BypassAutoSizeAxes"/> are ignored for automatic sizing.
/// Most notably, <see cref="Drawable.RelativePositionAxes"/> and <see cref="Drawable.RelativeSizeAxes"/> of children
/// do not affect automatic sizing to avoid circular size dependencies.
/// It is not allowed to manually set <see cref="Drawable.Size"/> (or <see cref="Drawable.Width"/> / <see cref="Drawable.Height"/>)
/// on any <see cref="Axes"/> which are automatically sized.
/// </summary>
public new Axes AutoSizeAxes
{
get => base.AutoSizeAxes;
set
{
base.AutoSizeAxes = value;
updateGridSize();
}
}
/// <summary>
/// The total number of rows in the content, including the header.
/// </summary>
private int totalRows => (content?.GetLength(0) ?? 0) + (ShowHeaders ? 1 : 0);
/// <summary>
/// The total number of columns in the content, including the header.
/// </summary>
private int totalColumns
{
get
{
if (columns == null || !showHeaders)
return content?.GetLength(1) ?? 0;
return Math.Max(columns.Length, content?.GetLength(1) ?? 0);
}
}
/// <summary>
/// Adds content to the underlying grid.
/// </summary>
private void updateContent()
{
grid.Content = getContentWithHeaders().ToJagged();
grid.ColumnDimensions = columns.Select(c => c.Dimension).ToArray();
grid.RowDimensions = Enumerable.Repeat(RowSize, totalRows).ToArray();
updateAnchors();
}
/// <summary>
/// Adds headers, if required, and returns the resulting content. <see cref="content"/> is not modified in the process.
/// </summary>
/// <returns>The content, with headers added if required.</returns>
private Drawable[,] getContentWithHeaders()
{
if (!ShowHeaders || Columns == null || Columns.Length == 0)
return content;
int rowCount = totalRows;
int columnCount = totalColumns;
var result = new Drawable[rowCount, columnCount];
for (int row = 0; row < rowCount; row++)
{
for (int col = 0; col < columnCount; col++)
{
if (row == 0)
result[row, col] = CreateHeader(col, col >= Columns?.Length ? null : Columns?[col]);
else if (col < content.GetLength(1))
result[row, col] = content[row - 1, col];
}
}
return result;
}
/// <summary>
/// Ensures that all cells have the correct anchors defined by <see cref="Columns"/>.
/// </summary>
private void updateAnchors()
{
if (grid.Content == null)
return;
int rowCount = totalRows;
int columnCount = totalColumns;
for (int row = 0; row < rowCount; row++)
{
for (int col = 0; col < columnCount; col++)
{
if (col >= columns.Length)
break;
Drawable child = grid.Content[row][col];
if (child == null)
continue;
child.Origin = columns[col].Anchor;
child.Anchor = columns[col].Anchor;
}
}
}
/// <summary>
/// Keeps the grid autosized in our autosized axes, and relative-sized in our non-autosized axes.
/// </summary>
private void updateGridSize()
{
grid.RelativeSizeAxes = Axes.None;
grid.AutoSizeAxes = Axes.None;
if ((AutoSizeAxes & Axes.X) == 0)
grid.RelativeSizeAxes |= Axes.X;
else
grid.AutoSizeAxes |= Axes.X;
if ((AutoSizeAxes & Axes.Y) == 0)
grid.RelativeSizeAxes |= Axes.Y;
else
grid.AutoSizeAxes |= Axes.Y;
}
/// <summary>
/// Creates the content for a cell in the header row of the table.
/// </summary>
/// <param name="index">The column index.</param>
/// <param name="column">The column definition.</param>
/// <returns>The cell content.</returns>
protected virtual Drawable CreateHeader(int index, [CanBeNull] TableColumn column) => new SpriteText { Text = column?.Header ?? string.Empty };
}
/// <summary>
/// Defines a column of the <see cref="TableContainer"/>.
/// </summary>
public class TableColumn
{
/// <summary>
/// The text to be displayed in the cell.
/// </summary>
public readonly string Header;
/// <summary>
/// The anchor of all cells in this column of the <see cref="TableContainer"/>.
/// </summary>
public readonly Anchor Anchor;
/// <summary>
/// The dimension of the column in the table.
/// </summary>
public readonly Dimension Dimension;
/// <summary>
/// Constructs a new <see cref="TableColumn"/>.
/// </summary>
/// <param name="header">The text to be displayed in the cell.</param>
/// <param name="anchor">The anchor of all cells in this column of the <see cref="TableContainer"/>.</param>
/// <param name="dimension">The dimension of the column in the table.</param>
public TableColumn(string header = null, Anchor anchor = Anchor.TopLeft, Dimension dimension = null)
{
Header = header ?? "";
Anchor = anchor;
Dimension = dimension ?? new Dimension();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.Mget11
{
public partial class Mget11YamlTests
{
public class Mget1170SourceFilteringYamlBase : YamlTestsBase
{
public Mget1170SourceFilteringYamlBase() : base()
{
//do index
_body = new {
include= new {
field1= "v1",
field2= "v2"
},
count= "1"
};
this.Do(()=> _client.Index("test_1", "test", "1", _body));
//do index
_body = new {
include= new {
field1= "v1",
field2= "v2"
},
count= "1"
};
this.Do(()=> _client.Index("test_1", "test", "2", _body));
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class SourceFilteringTrueFalse2Tests : Mget1170SourceFilteringYamlBase
{
[Test]
public void SourceFilteringTrueFalse2Test()
{
//do mget
_body = new {
docs= new dynamic[] {
new {
_index= "test_1",
_type= "test",
_id= "1",
_source= "false"
},
new {
_index= "test_1",
_type= "test",
_id= "2",
_source= "true"
}
}
};
this.Do(()=> _client.Mget(_body));
//match _response.docs[0]._id:
this.IsMatch(_response.docs[0]._id, 1);
//is_false _response.docs[0]._source;
this.IsFalse(_response.docs[0]._source);
//match _response.docs[1]._id:
this.IsMatch(_response.docs[1]._id, 2);
//is_true _response.docs[1]._source;
this.IsTrue(_response.docs[1]._source);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class SourceFilteringIncludeField3Tests : Mget1170SourceFilteringYamlBase
{
[Test]
public void SourceFilteringIncludeField3Test()
{
//do mget
_body = new {
docs= new dynamic[] {
new {
_index= "test_1",
_type= "test",
_id= "1",
_source= "include.field1"
},
new {
_index= "test_1",
_type= "test",
_id= "2",
_source= new [] {
"include.field1"
}
}
}
};
this.Do(()=> _client.Mget(_body));
//match _response.docs[0]._source:
this.IsMatch(_response.docs[0]._source, new {
include= new {
field1= "v1"
}
});
//match _response.docs[1]._source:
this.IsMatch(_response.docs[1]._source, new {
include= new {
field1= "v1"
}
});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class SourceFilteringIncludeNestedField4Tests : Mget1170SourceFilteringYamlBase
{
[Test]
public void SourceFilteringIncludeNestedField4Test()
{
//do mget
_body = new {
docs= new dynamic[] {
new {
_index= "test_1",
_type= "test",
_id= "1",
_source= new {
include= "include.field1"
}
},
new {
_index= "test_1",
_type= "test",
_id= "2",
_source= new {
include= new [] {
"include.field1"
}
}
}
}
};
this.Do(()=> _client.Mget(_body));
//match _response.docs[0]._source:
this.IsMatch(_response.docs[0]._source, new {
include= new {
field1= "v1"
}
});
//match _response.docs[1]._source:
this.IsMatch(_response.docs[1]._source, new {
include= new {
field1= "v1"
}
});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class SourceFilteringExcludeField5Tests : Mget1170SourceFilteringYamlBase
{
[Test]
public void SourceFilteringExcludeField5Test()
{
//do mget
_body = new {
docs= new dynamic[] {
new {
_index= "test_1",
_type= "test",
_id= "1",
_source= new {
include= new [] {
"include"
},
exclude= new [] {
"*.field2"
}
}
}
}
};
this.Do(()=> _client.Mget(_body));
//match _response.docs[0]._source:
this.IsMatch(_response.docs[0]._source, new {
include= new {
field1= "v1"
}
});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class SourceFilteringIdsAndTrueFalse6Tests : Mget1170SourceFilteringYamlBase
{
[Test]
public void SourceFilteringIdsAndTrueFalse6Test()
{
//do mget
_body = new {
ids= new [] {
"1",
"2"
}
};
this.Do(()=> _client.Mget("test_1", _body, nv=>nv
.AddQueryString("_source", @"false")
));
//is_false _response.docs[0]._source;
this.IsFalse(_response.docs[0]._source);
//is_false _response.docs[1]._source;
this.IsFalse(_response.docs[1]._source);
//do mget
_body = new {
ids= new [] {
"1",
"2"
}
};
this.Do(()=> _client.Mget("test_1", _body, nv=>nv
.AddQueryString("_source", @"true")
));
//is_true _response.docs[0]._source;
this.IsTrue(_response.docs[0]._source);
//is_true _response.docs[1]._source;
this.IsTrue(_response.docs[1]._source);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class SourceFilteringIdsAndIncludeField7Tests : Mget1170SourceFilteringYamlBase
{
[Test]
public void SourceFilteringIdsAndIncludeField7Test()
{
//do mget
_body = new {
ids= new [] {
"1",
"2"
}
};
this.Do(()=> _client.Mget("test_1", _body, nv=>nv
.AddQueryString("_source", @"include.field1")
));
//match _response.docs[0]._source:
this.IsMatch(_response.docs[0]._source, new {
include= new {
field1= "v1"
}
});
//match _response.docs[1]._source:
this.IsMatch(_response.docs[1]._source, new {
include= new {
field1= "v1"
}
});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class SourceFilteringIdsAndIncludeNestedField8Tests : Mget1170SourceFilteringYamlBase
{
[Test]
public void SourceFilteringIdsAndIncludeNestedField8Test()
{
//do mget
_body = new {
ids= new [] {
"1",
"2"
}
};
this.Do(()=> _client.Mget("test_1", _body, nv=>nv
.AddQueryString("_source_include", @"include.field1,count")
));
//match _response.docs[0]._source:
this.IsMatch(_response.docs[0]._source, new {
include= new {
field1= "v1"
},
count= "1"
});
//match _response.docs[1]._source:
this.IsMatch(_response.docs[1]._source, new {
include= new {
field1= "v1"
},
count= "1"
});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class SourceFilteringIdsAndExcludeField9Tests : Mget1170SourceFilteringYamlBase
{
[Test]
public void SourceFilteringIdsAndExcludeField9Test()
{
//do mget
_body = new {
ids= new [] {
"1",
"2"
}
};
this.Do(()=> _client.Mget("test_1", _body, nv=>nv
.AddQueryString("_source_include", @"include")
.AddQueryString("_source_exclude", @"*.field2")
));
//match _response.docs[0]._source:
this.IsMatch(_response.docs[0]._source, new {
include= new {
field1= "v1"
}
});
//match _response.docs[1]._source:
this.IsMatch(_response.docs[1]._source, new {
include= new {
field1= "v1"
}
});
}
}
}
}
| |
using System;
using System.Collections.Generic;
using IdmNet.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
// ReSharper disable ObjectCreationAsStatement
// ReSharper disable UseObjectOrCollectionInitializer
namespace IdmNet.Models.Tests
{
[TestClass]
public class WorkflowInstanceTests
{
private WorkflowInstance _it;
public WorkflowInstanceTests()
{
_it = new WorkflowInstance();
}
[TestMethod]
public void It_has_a_paremeterless_constructor()
{
Assert.AreEqual("WorkflowInstance", _it.ObjectType);
}
[TestMethod]
public void It_has_a_constructor_that_takes_an_IdmResource()
{
var resource = new IdmResource
{
DisplayName = "My Display Name",
Creator = new Person { DisplayName = "Creator Display Name", ObjectID = "Creator ObjectID"},
};
var it = new WorkflowInstance(resource);
Assert.AreEqual("WorkflowInstance", it.ObjectType);
Assert.AreEqual("My Display Name", it.DisplayName);
Assert.AreEqual("Creator Display Name", it.Creator.DisplayName);
}
[TestMethod]
public void It_has_a_constructor_that_takes_an_IdmResource_without_Creator()
{
var resource = new IdmResource
{
DisplayName = "My Display Name",
};
var it = new WorkflowInstance(resource);
Assert.AreEqual("My Display Name", it.DisplayName);
Assert.IsNull(it.Creator);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void It_throws_when_you_try_to_set_ObjectType_to_anything_other_than_its_primary_ObjectType()
{
_it.ObjectType = "Invalid Object Type";
}
[TestMethod]
public void It_has_Request_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.Request);
}
[TestMethod]
public void It_has_Request_which_can_be_set_back_to_null()
{
// Arrange
var testRequest = new Request { DisplayName = "Test Request" };
_it.Request = testRequest;
// Act
_it.Request = null;
// Assert
Assert.IsNull(_it.Request);
}
[TestMethod]
public void It_can_get_and_set_Request()
{
// Act
var testRequest = new Request { DisplayName = "Test Request" };
_it.Request = testRequest;
// Assert
Assert.AreEqual(testRequest.DisplayName, _it.Request.DisplayName);
}
[TestMethod]
public void It_has_Requestor_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.Requestor);
}
[TestMethod]
public void It_has_Requestor_which_can_be_set_back_to_null()
{
// Arrange
var testIdmResource = new IdmResource { DisplayName = "Test IdmResource" };
_it.Requestor = testIdmResource;
// Act
_it.Requestor = null;
// Assert
Assert.IsNull(_it.Requestor);
}
[TestMethod]
public void It_can_get_and_set_Requestor()
{
// Act
var testIdmResource = new IdmResource { DisplayName = "Test IdmResource" };
_it.Requestor = testIdmResource;
// Assert
Assert.AreEqual(testIdmResource.DisplayName, _it.Requestor.DisplayName);
}
[TestMethod]
public void It_has_Target_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.Target);
}
[TestMethod]
public void It_has_Target_which_can_be_set_back_to_null()
{
// Arrange
var testIdmResource = new IdmResource { DisplayName = "Test IdmResource" };
_it.Target = testIdmResource;
// Act
_it.Target = null;
// Assert
Assert.IsNull(_it.Target);
}
[TestMethod]
public void It_can_get_and_set_Target()
{
// Act
var testIdmResource = new IdmResource { DisplayName = "Test IdmResource" };
_it.Target = testIdmResource;
// Assert
Assert.AreEqual(testIdmResource.DisplayName, _it.Target.DisplayName);
}
[TestMethod]
public void It_has_WorkflowDefinition_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.WorkflowDefinition);
}
[TestMethod]
public void It_has_WorkflowDefinition_which_can_be_set_back_to_null()
{
// Arrange
var testWorkflowDefinition = new WorkflowDefinition { DisplayName = "Test WorkflowDefinition" };
_it.WorkflowDefinition = testWorkflowDefinition;
// Act
_it.WorkflowDefinition = null;
// Assert
Assert.IsNull(_it.WorkflowDefinition);
}
[TestMethod]
public void It_can_get_and_set_WorkflowDefinition()
{
// Act
var testWorkflowDefinition = new WorkflowDefinition { DisplayName = "Test WorkflowDefinition" };
_it.WorkflowDefinition = testWorkflowDefinition;
// Assert
Assert.AreEqual(testWorkflowDefinition.DisplayName, _it.WorkflowDefinition.DisplayName);
}
[TestMethod]
public void It_can_get_and_set_WorkflowStatus()
{
// Act
_it.WorkflowStatus = "A string";
// Assert
Assert.AreEqual("A string", _it.WorkflowStatus);
}
[TestMethod]
public void It_has_WorkflowStatusDetail_which_is_null_by_default()
{
// Assert
Assert.IsNull(_it.WorkflowStatusDetail);
}
[TestMethod]
public void It_has_WorkflowStatusDetail_which_can_be_set_back_to_null()
{
// Arrange
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
_it.WorkflowStatusDetail = list;
// Act
_it.WorkflowStatusDetail = null;
// Assert
Assert.IsNull(_it.WorkflowStatusDetail);
}
[TestMethod]
public void It_can_get_and_set_WorkflowStatusDetail()
{
var subObject1 = "foo1";
var subObject2 = "foo2";
var list = new List<string> { subObject1, subObject2 };
// Act
_it.WorkflowStatusDetail = list;
// Assert
Assert.AreEqual("foo1", _it.WorkflowStatusDetail[0]);
Assert.AreEqual("foo2", _it.WorkflowStatusDetail[1]);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Collections;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Security;
namespace System.Runtime.InteropServices.WindowsRuntime
{
internal sealed class CLRIReferenceImpl<T> : CLRIPropertyValueImpl, IReference<T>, IGetProxyTarget
{
private T _value;
public CLRIReferenceImpl(PropertyType type, T obj)
: base(type, obj)
{
BCLDebug.Assert(obj != null, "Must not be null");
_value = obj;
}
public T Value {
get { return _value; }
}
public override string ToString()
{
if (_value != null)
{
return _value.ToString();
}
else
{
return base.ToString();
}
}
object IGetProxyTarget.GetTarget()
{
return (object)_value;
}
// We have T in an IReference<T>. Need to QI for IReference<T> with the appropriate GUID, call
// the get_Value property, allocate an appropriately-sized managed object, marshal the native object
// to the managed object, and free the native method. Also we want the return value boxed (aka normal value type boxing).
//
// This method is called by VM. Mark the method with FriendAccessAllowed attribute to ensure that the unreferenced method
// optimization skips it and the code will be saved into NGen image.
[System.Runtime.CompilerServices.FriendAccessAllowed]
internal static Object UnboxHelper(Object wrapper)
{
Contract.Requires(wrapper != null);
IReference<T> reference = (IReference<T>) wrapper;
Contract.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed.");
return reference.Value;
}
}
// T can be any WinRT-compatible type
internal sealed class CLRIReferenceArrayImpl<T> : CLRIPropertyValueImpl,
IGetProxyTarget,
IReferenceArray<T>,
IList // Jupiter data binding needs IList/IEnumerable
{
private T[] _value;
private IList _list;
public CLRIReferenceArrayImpl(PropertyType type, T[] obj)
: base(type, obj)
{
BCLDebug.Assert(obj != null, "Must not be null");
_value = obj;
_list = (IList) _value;
}
public T[] Value {
get { return _value; }
}
public override string ToString()
{
if (_value != null)
{
return _value.ToString();
}
else
{
return base.ToString();
}
}
//
// IEnumerable methods. Used by data-binding in Jupiter when you try to data bind
// against a managed array
//
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_value).GetEnumerator();
}
//
// IList & ICollection methods.
// This enables two-way data binding and index access in Jupiter
//
Object IList.this[int index] {
get
{
return _list[index];
}
set
{
_list[index] = value;
}
}
int IList.Add(Object value)
{
return _list.Add(value);
}
bool IList.Contains(Object value)
{
return _list.Contains(value);
}
void IList.Clear()
{
_list.Clear();
}
bool IList.IsReadOnly
{
get
{
return _list.IsReadOnly;
}
}
bool IList.IsFixedSize
{
get
{
return _list.IsFixedSize;
}
}
int IList.IndexOf(Object value)
{
return _list.IndexOf(value);
}
void IList.Insert(int index, Object value)
{
_list.Insert(index, value);
}
void IList.Remove(Object value)
{
_list.Remove(value);
}
void IList.RemoveAt(int index)
{
_list.RemoveAt(index);
}
void ICollection.CopyTo(Array array, int index)
{
_list.CopyTo(array, index);
}
int ICollection.Count
{
get
{
return _list.Count;
}
}
Object ICollection.SyncRoot
{
get
{
return _list.SyncRoot;
}
}
bool ICollection.IsSynchronized
{
get
{
return _list.IsSynchronized;
}
}
object IGetProxyTarget.GetTarget()
{
return (object)_value;
}
// We have T in an IReferenceArray<T>. Need to QI for IReferenceArray<T> with the appropriate GUID, call
// the get_Value property, allocate an appropriately-sized managed object, marshal the native object
// to the managed object, and free the native method.
//
// This method is called by VM. Mark the method with FriendAccessAllowed attribute to ensure that the unreferenced method
// optimization skips it and the code will be saved into NGen image.
[System.Runtime.CompilerServices.FriendAccessAllowed]
internal static Object UnboxHelper(Object wrapper)
{
Contract.Requires(wrapper != null);
IReferenceArray<T> reference = (IReferenceArray<T>)wrapper;
Contract.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed.");
T[] marshaled = reference.Value;
return marshaled;
}
}
// For creating instances of Windows Runtime's IReference<T> and IReferenceArray<T>.
internal static class IReferenceFactory
{
internal static readonly Type s_pointType = Type.GetType("Windows.Foundation.Point, " + AssemblyRef.SystemRuntimeWindowsRuntime);
internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, " + AssemblyRef.SystemRuntimeWindowsRuntime);
internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, " + AssemblyRef.SystemRuntimeWindowsRuntime);
[SecuritySafeCritical]
internal static Object CreateIReference(Object obj)
{
Contract.Requires(obj != null, "Null should not be boxed.");
Contract.Ensures(Contract.Result<Object>() != null);
Type type = obj.GetType();
if (type.IsArray)
return CreateIReferenceArray((Array) obj);
if (type == typeof(int))
return new CLRIReferenceImpl<int>(PropertyType.Int32, (int)obj);
if (type == typeof(String))
return new CLRIReferenceImpl<String>(PropertyType.String, (String)obj);
if (type == typeof(byte))
return new CLRIReferenceImpl<byte>(PropertyType.UInt8, (byte)obj);
if (type == typeof(short))
return new CLRIReferenceImpl<short>(PropertyType.Int16, (short)obj);
if (type == typeof(ushort))
return new CLRIReferenceImpl<ushort>(PropertyType.UInt16, (ushort)obj);
if (type == typeof(uint))
return new CLRIReferenceImpl<uint>(PropertyType.UInt32, (uint)obj);
if (type == typeof(long))
return new CLRIReferenceImpl<long>(PropertyType.Int64, (long)obj);
if (type == typeof(ulong))
return new CLRIReferenceImpl<ulong>(PropertyType.UInt64, (ulong)obj);
if (type == typeof(float))
return new CLRIReferenceImpl<float>(PropertyType.Single, (float)obj);
if (type == typeof(double))
return new CLRIReferenceImpl<double>(PropertyType.Double, (double)obj);
if (type == typeof(char))
return new CLRIReferenceImpl<char>(PropertyType.Char16, (char)obj);
if (type == typeof(bool))
return new CLRIReferenceImpl<bool>(PropertyType.Boolean, (bool)obj);
if (type == typeof(Guid))
return new CLRIReferenceImpl<Guid>(PropertyType.Guid, (Guid)obj);
if (type == typeof(DateTimeOffset))
return new CLRIReferenceImpl<DateTimeOffset>(PropertyType.DateTime, (DateTimeOffset)obj);
if (type == typeof(TimeSpan))
return new CLRIReferenceImpl<TimeSpan>(PropertyType.TimeSpan, (TimeSpan)obj);
if (type == typeof(Object))
return new CLRIReferenceImpl<Object>(PropertyType.Inspectable, (Object)obj);
if (type == typeof(RuntimeType))
{ // If the type is System.RuntimeType, we want to use System.Type marshaler (it's parent of the type)
return new CLRIReferenceImpl<Type>(PropertyType.Other, (Type)obj);
}
// Handle arbitrary WinRT-compatible value types, and recognize a few special types.
PropertyType? propType = null;
if (type == s_pointType)
{
propType = PropertyType.Point;
}
else if (type == s_rectType)
{
propType = PropertyType.Rect;
}
else if (type == s_sizeType)
{
propType = PropertyType.Size;
}
else if (type.IsValueType || obj is Delegate)
{
propType = PropertyType.Other;
}
if (propType.HasValue)
{
Type specificType = typeof(CLRIReferenceImpl<>).MakeGenericType(type);
return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj });
}
Contract.Assert(false, "We should not see non-WinRT type here");
return null;
}
[SecuritySafeCritical]
internal static Object CreateIReferenceArray(Array obj)
{
Contract.Requires(obj != null);
Contract.Requires(obj.GetType().IsArray);
Contract.Ensures(Contract.Result<Object>() != null);
Type type = obj.GetType().GetElementType();
Contract.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray);
if (type == typeof(int))
return new CLRIReferenceArrayImpl<int>(PropertyType.Int32Array, (int[])obj);
if (type == typeof(String))
return new CLRIReferenceArrayImpl<String>(PropertyType.StringArray, (String[])obj);
if (type == typeof(byte))
return new CLRIReferenceArrayImpl<byte>(PropertyType.UInt8Array, (byte[])obj);
if (type == typeof(short))
return new CLRIReferenceArrayImpl<short>(PropertyType.Int16Array, (short[])obj);
if (type == typeof(ushort))
return new CLRIReferenceArrayImpl<ushort>(PropertyType.UInt16Array, (ushort[])obj);
if (type == typeof(uint))
return new CLRIReferenceArrayImpl<uint>(PropertyType.UInt32Array, (uint[])obj);
if (type == typeof(long))
return new CLRIReferenceArrayImpl<long>(PropertyType.Int64Array, (long[])obj);
if (type == typeof(ulong))
return new CLRIReferenceArrayImpl<ulong>(PropertyType.UInt64Array, (ulong[])obj);
if (type == typeof(float))
return new CLRIReferenceArrayImpl<float>(PropertyType.SingleArray, (float[])obj);
if (type == typeof(double))
return new CLRIReferenceArrayImpl<double>(PropertyType.DoubleArray, (double[])obj);
if (type == typeof(char))
return new CLRIReferenceArrayImpl<char>(PropertyType.Char16Array, (char[])obj);
if (type == typeof(bool))
return new CLRIReferenceArrayImpl<bool>(PropertyType.BooleanArray, (bool[])obj);
if (type == typeof(Guid))
return new CLRIReferenceArrayImpl<Guid>(PropertyType.GuidArray, (Guid[])obj);
if (type == typeof(DateTimeOffset))
return new CLRIReferenceArrayImpl<DateTimeOffset>(PropertyType.DateTimeArray, (DateTimeOffset[])obj);
if (type == typeof(TimeSpan))
return new CLRIReferenceArrayImpl<TimeSpan>(PropertyType.TimeSpanArray, (TimeSpan[])obj);
if (type == typeof(Type))
{ // Note: The array type will be System.Type, not System.RuntimeType
return new CLRIReferenceArrayImpl<Type>(PropertyType.OtherArray, (Type[])obj);
}
PropertyType? propType = null;
if (type == s_pointType)
{
propType = PropertyType.PointArray;
}
else if (type == s_rectType)
{
propType = PropertyType.RectArray;
}
else if (type == s_sizeType)
{
propType = PropertyType.SizeArray;
}
else if (type.IsValueType)
{
// note that KeyValuePair`2 is a reference type on the WinRT side so the array
// must be wrapped with CLRIReferenceArrayImpl<Object>
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>))
{
Object[] objArray = new Object[obj.Length];
for (int i = 0; i < objArray.Length; i++)
{
objArray[i] = obj.GetValue(i);
}
obj = objArray;
}
else
{
propType = PropertyType.OtherArray;
}
}
else if (typeof(Delegate).IsAssignableFrom(type))
{
propType = PropertyType.OtherArray;
}
if (propType.HasValue)
{
// All WinRT value type will be Property.Other
Type specificType = typeof(CLRIReferenceArrayImpl<>).MakeGenericType(type);
return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj });
}
else
{
// All WinRT reference type (including arbitary managed type) will be PropertyType.ObjectArray
return new CLRIReferenceArrayImpl<Object>(PropertyType.InspectableArray, (Object[])obj);
}
}
}
}
| |
#if ANDROID || IOS
#define REQUIRES_PRIMARY_THREAD_LOADING
#endif
#region Using
using System;
using System.Collections.Generic;
using System.Reflection;
using FlatRedBall.Math;
using FlatRedBall.Gui;
using FlatRedBall.Instructions;
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Graphics;
using FlatRedBall.Utilities;
using System.Threading;
using FlatRedBall.Input;
using FlatRedBall.IO;
#if !SILVERLIGHT
#endif
#endregion
// Test
namespace FlatRedBall.Screens
{
#region Enums
public enum AsyncLoadingState
{
NotStarted,
LoadingScreen,
Done
}
#endregion
public class Screen : IInstructable
{
#region Fields
int mNumberOfThreadsBeforeAsync = -1;
protected bool IsPaused = false;
protected double mTimeScreenWasCreated;
protected double mAccumulatedPausedTime = 0;
protected Layer mLayer;
private string mContentManagerName;
protected Scene mLastLoadedScene;
private bool mIsActivityFinished;
private string mNextScreen;
private bool mManageSpriteGrids;
internal Screen mNextScreenToLoadAsync;
#if !FRB_MDX
Action ActivatingAction;
Action DeactivatingAction;
#endif
#endregion
#region Properties
/// <summary>
/// The list of instructions owned
/// by this screen.
/// </summary>
/// <remarks>
/// These instructions will be automatically
/// executed based off of time. Execution of
/// these instructions is automatically handled
/// by the InstructionManager.
/// </remarks>
public InstructionList Instructions
{
get;
private set;
}
public bool ShouldRemoveLayer
{
get;
set;
}
/// <summary>
/// Returns how much time the Screen has spent paused
/// </summary>
public double AccumulatedPauseTime
{
get
{
// Internally we just use the accumulated pause time
// without considering when the Screen was started. But
// for external reporting we need to report just the actual
// paused time.
return mAccumulatedPausedTime - mTimeScreenWasCreated;
}
}
public double PauseAdjustedCurrentTime
{
get { return TimeManager.CurrentTime - mAccumulatedPausedTime; }
}
public Action ScreenDestroy { get; set; }
public int ActivityCallCount
{
get;
set;
}
public string ContentManagerName
{
get { return mContentManagerName; }
}
#region XML Docs
/// <summary>
/// Gets and sets whether the activity is finished for a particular screen.
/// </summary>
/// <remarks>
/// If activity is finished, then the ScreenManager or parent
/// screen (if the screen is a popup) knows to destroy the screen
/// and loads the NextScreen class.</remarks>
#endregion
public bool IsActivityFinished
{
get { return mIsActivityFinished; }
set
{
mIsActivityFinished = value;
}
}
public AsyncLoadingState AsyncLoadingState
{
get;
private set;
}
public Layer Layer
{
get { return mLayer; }
set { mLayer = value; }
}
public bool ManageSpriteGrids
{
get { return mManageSpriteGrids; }
set { mManageSpriteGrids = value; }
}
#region XML Docs
/// <summary>
/// The fully qualified path of the Screen-inheriting class that this screen is
/// to link to.
/// </summary>
/// <remarks>
/// This property is read by the ScreenManager when IsActivityFinished is
/// set to true. Therefore, this must always be set to some value before
/// or in the same frame as when IsActivityFinished is set to true.
/// </remarks>
#endregion
public string NextScreen
{
get { return mNextScreen; }
set { mNextScreen = value; }
}
public bool IsMovingBack { get; set; }
protected bool UnloadsContentManagerWhenDestroyed
{
get;
set;
}
public bool HasDrawBeenCalled
{
get;
internal set;
}
#endregion
#region Methods
#region Constructor
public Screen(string contentManagerName)
{
this.Instructions = new InstructionList();
ShouldRemoveLayer = true;
UnloadsContentManagerWhenDestroyed = true;
mContentManagerName = contentManagerName;
mManageSpriteGrids = true;
IsActivityFinished = false;
mLayer = ScreenManager.NextScreenLayer;
ActivatingAction = new Action(Activating);
DeactivatingAction = new Action(OnDeactivating);
StateManager.Current.Activating += ActivatingAction;
StateManager.Current.Deactivating += DeactivatingAction;
if (ScreenManager.ShouldActivateScreen)
{
Activating();
}
}
#endregion
#region Public Methods
public virtual void Activating()
{
this.PreActivate();// for generated code to override, to reload the statestack
this.OnActivate(PlatformServices.State);// for user created code
}
private void OnDeactivating()
{
this.PreDeactivate();// for generated code to override, to save the statestack
this.OnDeactivate(PlatformServices.State);// for user generated code;
}
#region Activation Methods
#if !FRB_MDX
protected virtual void OnActivate(StateManager state)
{
}
protected virtual void PreActivate()
{
}
protected virtual void OnDeactivate(StateManager state)
{
}
protected virtual void PreDeactivate()
{
}
#endif
#endregion
public virtual void Activity(bool firstTimeCalled)
{
if (IsPaused)
{
mAccumulatedPausedTime += TimeManager.SecondDifference;
}
// This needs to happen after popup activity
// in case the Screen creates a popup - we don't
// want 2 activity calls for one frame. We also want
// to make sure that popups have the opportunity to handle
// back calls so that the base doesn't get it.
if (PlatformServices.BackStackEnabled && InputManager.BackPressed && !firstTimeCalled)
{
this.HandleBackNavigation();
}
}
Type asyncScreenTypeToLoad = null;
public void StartAsyncLoad(Type type, Action afterLoaded = null)
{
StartAsyncLoad(type.FullName, afterLoaded);
}
public void StartAsyncLoad(string screenType, Action afterLoaded = null)
{
if (AsyncLoadingState == AsyncLoadingState.LoadingScreen)
{
#if DEBUG
throw new InvalidOperationException("This Screen is already loading a Screen of type " + asyncScreenTypeToLoad + ". This is a DEBUG-only exception");
#endif
}
else if (AsyncLoadingState == AsyncLoadingState.Done)
{
#if DEBUG
throw new InvalidOperationException("This Screen has already loaded a Screen of type " + asyncScreenTypeToLoad + ". This is a DEBUG-only exception");
#endif
}
else
{
AsyncLoadingState = AsyncLoadingState.LoadingScreen;
asyncScreenTypeToLoad = ScreenManager.MainAssembly.GetType(screenType);
if (asyncScreenTypeToLoad == null)
{
throw new Exception("Could not find the type " + screenType);
}
#if REQUIRES_PRIMARY_THREAD_LOADING
// We're going to do the "async" loading on the primary thread
// since we can't actually do it async.
PerformAsyncLoad();
if(afterLoaded != null)
{
afterLoaded();
}
#else
mNumberOfThreadsBeforeAsync = FlatRedBallServices.GetNumberOfThreadsToUse();
FlatRedBallServices.SetNumberOfThreadsToUse(1);
Action action;
if(afterLoaded == null)
{
action = (Action)PerformAsyncLoad;
}
else
{
action = () =>
{
PerformAsyncLoad();
// We're going to add this to the instruction manager so it executes on the main thread:
InstructionManager.AddSafe(new DelegateInstruction(afterLoaded));
};
}
#if WINDOWS_8 || UWP
System.Threading.Tasks.Task.Run(action);
#else
ThreadStart threadStart = new ThreadStart(action);
Thread thread = new Thread(threadStart);
thread.Start();
#endif
#endif
}
}
private void PerformAsyncLoad()
{
mNextScreenToLoadAsync = (Screen)Activator.CreateInstance(asyncScreenTypeToLoad, new object[0]);
// Don't add it to the manager!
mNextScreenToLoadAsync.Initialize(addToManagers:false);
AsyncLoadingState = AsyncLoadingState.Done;
}
public virtual void Initialize(bool addToManagers)
{
}
public virtual void AddToManagers()
{
// We want to start the timer when we actually add to managers - this is when the activity for the Screen starts
mAccumulatedPausedTime = TimeManager.CurrentTime;
mTimeScreenWasCreated = TimeManager.CurrentTime;
}
public virtual void Destroy()
{
#if !FRB_MDX
StateManager.Current.Activating -= ActivatingAction;
StateManager.Current.Deactivating -= DeactivatingAction;
#endif
if (mLastLoadedScene != null)
{
mLastLoadedScene.Clear();
}
FlatRedBall.Debugging.Debugger.DestroyText();
// It's common for users to forget to add Particle Sprites
// to the mSprites SpriteList. This will either create leftover
// particles when the next screen loads or will throw an assert when
// the ScreenManager checks if there are any leftover Sprites. To make
// things easier we'll just clear the Particle Sprites here.
bool isPopup = this != ScreenManager.CurrentScreen;
if (!isPopup)
SpriteManager.RemoveAllParticleSprites();
if (UnloadsContentManagerWhenDestroyed && mContentManagerName != FlatRedBallServices.GlobalContentManager)
{
FlatRedBallServices.Unload(mContentManagerName);
FlatRedBallServices.Clean();
}
if (ShouldRemoveLayer && mLayer != null)
{
SpriteManager.RemoveLayer(mLayer);
}
if (IsPaused)
{
UnpauseThisScreen();
}
GuiManager.Cursor.IgnoreNextClick = true;
if(mNumberOfThreadsBeforeAsync != -1)
{
FlatRedBallServices.SetNumberOfThreadsToUse(mNumberOfThreadsBeforeAsync);
}
if (ScreenDestroy != null)
ScreenDestroy();
}
protected virtual void PauseThisScreen()
{
//base.PauseThisScreen();
this.IsPaused = true;
InstructionManager.PauseEngine();
}
protected virtual void UnpauseThisScreen()
{
InstructionManager.UnpauseEngine();
this.IsPaused = false;
}
/// <summary>
/// Returns the number of seconds since the argument time for the current screen, considering pausing.
/// </summary>
/// <remarks>
/// Each screen has an internal timer which keeps track of how much time has passed since it has been constructed.
/// This timer always begins at 0. Therefore, the following code will always tell you how long the screen has been alive:
/// var timeScreenHasBeenAlive = ScreenInstance.PauseAdjustedSecondsSince(0);
/// </remarks>
/// <param name="time">The time from which to check how much time has passed.</param>
/// <returns>How much time has passed since the parameter value.</returns>
public double PauseAdjustedSecondsSince(double time)
{
return PauseAdjustedCurrentTime - time;
}
#region XML Docs
/// <summary>Tells the screen that we are done and wish to move to the
/// supplied screen</summary>
/// <param>Fully Qualified Type of the screen to move to</param>
#endregion
public void MoveToScreen(string screenClass)
{
IsActivityFinished = true;
NextScreen = screenClass;
}
public void MoveToScreen(Type screenType)
{
IsActivityFinished = true;
NextScreen = screenType.FullName;
}
public void RestartScreen(bool reloadContent)
{
if (reloadContent == false)
{
UnloadsContentManagerWhenDestroyed = false;
}
MoveToScreen(this.GetType());
}
#endregion
#region Protected Methods
/// <param name="state">This should be a valid enum value of the concrete screen type.</param>
public virtual void MoveToState(int state)
{
// no-op
}
/// <summary>Default implementation tells the screen manager to finish this screen's activity and navigate
/// to the previous screen on the backstack.</summary>
/// <remarks>Override this method if you want to have custom behavior when the back button is pressed.</remarks>
protected virtual void HandleBackNavigation()
{
}
#endregion
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="OdbcHandle.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;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Runtime.ConstrainedExecution;
namespace System.Data.Odbc {
internal abstract class OdbcHandle : SafeHandle {
private ODBC32.SQL_HANDLE _handleType;
private OdbcHandle _parentHandle;
protected OdbcHandle(ODBC32.SQL_HANDLE handleType, OdbcHandle parentHandle) : base(IntPtr.Zero, true) {
_handleType = handleType;
bool mustRelease = false;
ODBC32.RetCode retcode = ODBC32.RetCode.SUCCESS;
// using ConstrainedRegions to make the native ODBC call and AddRef the parent
RuntimeHelpers.PrepareConstrainedRegions();
try {
// validate handleType
switch(handleType) {
case ODBC32.SQL_HANDLE.ENV:
Debug.Assert(null == parentHandle, "did not expect a parent handle");
retcode = UnsafeNativeMethods.SQLAllocHandle(handleType, IntPtr.Zero, out base.handle);
break;
case ODBC32.SQL_HANDLE.DBC:
case ODBC32.SQL_HANDLE.STMT:
// must addref before calling native so it won't be released just after
Debug.Assert(null != parentHandle, "expected a parent handle"); // safehandle can't be null
parentHandle.DangerousAddRef(ref mustRelease);
retcode = UnsafeNativeMethods.SQLAllocHandle(handleType, parentHandle, out base.handle);
break;
// case ODBC32.SQL_HANDLE.DESC:
default:
Debug.Assert(false, "unexpected handleType");
break;
}
}
finally {
if (mustRelease) {
switch(handleType) {
case ODBC32.SQL_HANDLE.DBC:
case ODBC32.SQL_HANDLE.STMT:
if (IntPtr.Zero != base.handle) {
// must assign _parentHandle after a handle is actually created
// since ReleaseHandle will only call DangerousRelease if a handle exists
_parentHandle = parentHandle;
}
else {
// without a handle, ReleaseHandle may not be called
parentHandle.DangerousRelease();
}
break;
}
}
}
Bid.TraceSqlReturn("<odbc.SQLAllocHandle|API|ODBC|RET> %08X{SQLRETURN}\n", retcode);
if((ADP.PtrZero == base.handle) || (ODBC32.RetCode.SUCCESS != retcode)) {
//
throw ODBC.CantAllocateEnvironmentHandle(retcode);
}
}
internal OdbcHandle(OdbcStatementHandle parentHandle, ODBC32.SQL_ATTR attribute) : base(IntPtr.Zero, true) {
Debug.Assert((ODBC32.SQL_ATTR.APP_PARAM_DESC == attribute) || (ODBC32.SQL_ATTR.APP_ROW_DESC == attribute), "invalid attribute");
_handleType = ODBC32.SQL_HANDLE.DESC;
int cbActual;
ODBC32.RetCode retcode;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
// must addref before calling native so it won't be released just after
parentHandle.DangerousAddRef(ref mustRelease);
retcode = parentHandle.GetStatementAttribute(attribute, out base.handle, out cbActual);
}
finally {
if (mustRelease) {
if (IntPtr.Zero != base.handle) {
// must call DangerousAddRef after a handle is actually created
// since ReleaseHandle will only call DangerousRelease if a handle exists
_parentHandle = parentHandle;
}
else {
// without a handle, ReleaseHandle may not be called
parentHandle.DangerousRelease();
}
}
}
if (ADP.PtrZero == base.handle) {
throw ODBC.FailedToGetDescriptorHandle(retcode);
}
// no info-message handle on getting a descriptor handle
}
internal ODBC32.SQL_HANDLE HandleType {
get {
return _handleType;
}
}
public override bool IsInvalid {
get {
// we should not have a parent if we do not have a handle
return (IntPtr.Zero == base.handle);
}
}
override protected bool ReleaseHandle() {
// NOTE: The SafeHandle class guarantees this will be called exactly once and is non-interrutible.
IntPtr handle = base.handle;
base.handle = IntPtr.Zero;
if (IntPtr.Zero != handle) {
ODBC32.SQL_HANDLE handleType = HandleType;
switch (handleType) {
case ODBC32.SQL_HANDLE.DBC:
// Disconnect happens in OdbcConnectionHandle.ReleaseHandle
case ODBC32.SQL_HANDLE.ENV:
case ODBC32.SQL_HANDLE.STMT:
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLFreeHandle(handleType, handle);
Bid.TraceSqlReturn("<odbc.SQLFreeHandle|API|ODBC|RET> %08X{SQLRETURN}\n", retcode);
break;
case ODBC32.SQL_HANDLE.DESC:
// nothing to free on the handle
break;
// case 0: ThreadAbortException setting handle before HandleType
default:
Debug.Assert(ADP.PtrZero == handle, "unknown handle type");
break;
}
}
// If we ended up getting released, then we have to release
// our reference on our parent.
OdbcHandle parentHandle = _parentHandle;
_parentHandle = null;
if (null != parentHandle) {
parentHandle.DangerousRelease();
parentHandle = null;
}
return true;
}
internal ODBC32.RetCode GetDiagnosticField (out string sqlState) {
short cbActual;
// ODBC (MSDN) documents it expects a buffer large enough to hold 5(+L'\0') unicode characters
StringBuilder sb = new StringBuilder(6);
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetDiagFieldW(
HandleType,
this,
(short)1,
ODBC32.SQL_DIAG_SQLSTATE,
sb,
checked((short)(2*sb.Capacity)), // expects number of bytes, see \\kbinternal\kb\articles\294\1\69.HTM
out cbActual);
ODBC.TraceODBC(3, "SQLGetDiagFieldW", retcode);
if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)) {
sqlState = sb.ToString();
}
else {
sqlState = ADP.StrEmpty;
}
return retcode;
}
internal ODBC32.RetCode GetDiagnosticRecord(short record, out string sqlState, StringBuilder message, out int nativeError, out short cchActual) {
// ODBC (MSDN) documents it expects a buffer large enough to hold 4(+L'\0') unicode characters
StringBuilder sb = new StringBuilder(5);
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetDiagRecW(HandleType, this, record, sb, out nativeError, message, checked((short)message.Capacity), out cchActual);
ODBC.TraceODBC(3, "SQLGetDiagRecW", retcode);
if ((retcode == ODBC32.RetCode.SUCCESS) || (retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)) {
sqlState = sb.ToString();
}
else {
sqlState = ADP.StrEmpty;
}
return retcode;
}
}
sealed internal class OdbcDescriptorHandle : OdbcHandle {
internal OdbcDescriptorHandle(OdbcStatementHandle statementHandle, ODBC32.SQL_ATTR attribute) : base(statementHandle, attribute) {
}
internal ODBC32.RetCode GetDescriptionField(int i, ODBC32.SQL_DESC attribute, CNativeBuffer buffer, out int numericAttribute) {
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetDescFieldW(this, checked((short)i), attribute, buffer, buffer.ShortLength, out numericAttribute);
ODBC.TraceODBC(3, "SQLGetDescFieldW", retcode);
return retcode;
}
internal ODBC32.RetCode SetDescriptionField1(short ordinal, ODBC32.SQL_DESC type, IntPtr value) {
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLSetDescFieldW(this, ordinal, type, value, 0);
ODBC.TraceODBC(3, "SQLSetDescFieldW", retcode);
return retcode;
}
internal ODBC32.RetCode SetDescriptionField2(short ordinal, ODBC32.SQL_DESC type, HandleRef value) {
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLSetDescFieldW(this, ordinal, type, value, 0);
ODBC.TraceODBC(3, "SQLSetDescFieldW", retcode);
return retcode;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SubStream.cs" company="Microsoft">
// Copyright 2016 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.Blob
{
using System;
using System.IO;
using Microsoft.WindowsAzure.Storage.Core.Util;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using Microsoft.WindowsAzure.Storage.Core;
/// <summary>
/// A wrapper class that creates a logical substream from a region within an existing seekable stream.
/// Allows for concurrent, asynchronous read and seek operations on the wrapped stream.
/// Ensures thread-safe operations between related substream instances via a shared, user-supplied synchronization mutex.
/// This class will buffer read requests to minimize overhead on the underlying stream.
/// </summary>
internal sealed class SubStream : Stream
{
// Stream to be logically wrapped.
private Stream wrappedStream;
// Position in the wrapped stream at which the SubStream should logically begin.
private long streamBeginIndex;
// Total length of the substream.
private long substreamLength;
// Tracks the current position in the substream.
private long substreamCurrentIndex;
// Stream to manage read buffer, lazily initialized when read or seek operations commence.
private Lazy<MemoryStream> readBufferStream;
// Internal read buffer, lazily initialized when read or seek operations commence.
private Lazy<byte[]> readBuffer;
// Tracks the valid bytes remaining in the readBuffer
private int readBufferLength;
// Determines where to update the position of the readbuffer stream depending on the scenario)
private bool shouldSeek = false;
// Non-blocking semaphore for controlling read operations between related SubStream instances.
public SemaphoreSlim Mutex { get; set; }
// Current relative position in the substream.
public override long Position
{
get
{
return this.substreamCurrentIndex;
}
set
{
CommonUtility.AssertInBounds("Position", value, 0, this.substreamLength);
// Check if we can potentially advance substream position without reallocating the read buffer.
if (value >= this.substreamCurrentIndex)
{
long offset = value - this.substreamCurrentIndex;
// New position is within the valid bytes stored in the readBuffer.
if (offset <= this.readBufferLength)
{
this.readBufferLength -= (int)offset;
if (shouldSeek)
{
this.readBufferStream.Value.Seek(offset, SeekOrigin.Current);
}
}
else
{
// Resets the read buffer.
this.readBufferLength = 0;
this.readBufferStream.Value.Seek(0, SeekOrigin.End);
}
}
else
{
// Resets the read buffer.
this.readBufferLength = 0;
this.readBufferStream.Value.Seek(0, SeekOrigin.End);
}
this.substreamCurrentIndex = value;
}
}
// Total length of the substream.
public override long Length
{
get { return this.substreamLength; }
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return false; }
}
private void CheckDisposed()
{
if (this.wrappedStream == null)
{
throw new ObjectDisposedException("SubStreamWrapper");
}
}
protected override void Dispose(bool disposing)
{
this.wrappedStream = null;
this.readBufferStream = null;
this.readBuffer = null;
}
public override void Flush()
{
throw new NotSupportedException();
}
// Initiates the new buffer size to be used for read operations.
public int ReadBufferSize
{
get
{
return this.readBuffer.Value.Length;
}
set
{
if (value < 2 * Constants.DefaultBufferSize)
{
throw new ArgumentOutOfRangeException(string.Format(SR.ArgumentTooSmallError, "ReadBufferSize", 2 * Constants.DefaultBufferSize));
}
this.readBuffer = new Lazy<byte[]>(() => new byte[value]);
this.readBufferStream = new Lazy<MemoryStream>(() => new MemoryStream(this.readBuffer.Value, 0, value, true));
this.readBufferStream.Value.Seek(0, SeekOrigin.End);
}
}
/// <summary>
/// Creates a new SubStream instance.
/// </summary>
/// <param name="stream">A seekable source stream.</param>
/// <param name="streamBeginIndex">The index in the wrapped stream where the logical SubStream should begin.</param>
/// <param name="substreamLength">The length of the SubStream.</param>
/// <param name="globalSemaphore"> A <see cref="SemaphoreSlim"/> object that is shared between related SubStream instances.</param>
/// <remarks>
/// The source stream to be wrapped must be seekable.
/// The Semaphore object provided must have the initialCount thread parameter set to one to ensure only one concurrent request is granted at a time.
/// </remarks>
public SubStream(Stream stream, long streamBeginIndex, long substreamLength, SemaphoreSlim globalSemaphore)
{
if (stream == null)
{
throw new ArgumentNullException("Stream.");
}
else if (!stream.CanSeek)
{
throw new NotSupportedException("Stream must be seekable.");
}
else if (globalSemaphore == null)
{
throw new ArgumentNullException("globalSemaphore");
}
CommonUtility.AssertInBounds("streamBeginIndex", streamBeginIndex, 0, stream.Length);
this.streamBeginIndex = streamBeginIndex;
this.wrappedStream = stream;
this.Mutex = globalSemaphore;
this.substreamLength = Math.Min(substreamLength, stream.Length - streamBeginIndex);
this.readBufferLength = 0;
this.Position = 0;
this.ReadBufferSize = Constants.DefaultSubStreamBufferSize;
}
#if !(WINDOWS_RT || NETCORE)
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return this.ReadAsync(buffer, offset, count, CancellationToken.None).AsApm<int>(callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
CommonUtility.AssertNotNull("AsyncResult", asyncResult);
return ((Task<int>)asyncResult).Result;
}
#endif
/// <summary>
/// Reads a block of bytes asynchronously from the substream read buffer.
/// </summary>
/// <param name="buffer">When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read.</param>
/// <param name="cancellationToken">An object of type <see cref="CancellationToken"/> that propagates notification that operation should be canceled.</param>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the substream has been reached.</returns>
/// <remarks>
/// If the read request cannot be satisfied because the read buffer is empty or contains less than the requested number of the bytes,
/// the wrapped stream will be called to refill the read buffer.
/// Only one read request to the underlying wrapped stream will be allowed at a time and concurrent requests will be queued up by effect of the shared semaphore mutex.
/// </remarks>
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
this.CheckDisposed();
try
{
int readCount = this.CheckAdjustReadCount(count, offset, buffer.Length);
int bytesRead = await this.readBufferStream.Value.ReadAsync(buffer, offset, Math.Min(readCount, this.readBufferLength), cancellationToken).ConfigureAwait(false);
int bytesLeft = readCount - bytesRead;
// must adjust readbufferLength
this.shouldSeek = false;
this.Position += bytesRead;
if (bytesLeft > 0 && readBufferLength == 0)
{
this.readBufferStream.Value.Position = 0;
int bytesAdded =
await this.ReadAsyncHelper(this.readBuffer.Value, 0, this.readBuffer.Value.Length, cancellationToken).ConfigureAwait(false);
this.readBufferLength = bytesAdded;
if (bytesAdded > 0)
{
bytesLeft = Math.Min(bytesAdded, bytesLeft);
int secondRead = await this.readBufferStream.Value.ReadAsync(buffer, bytesRead + offset, bytesLeft, cancellationToken).ConfigureAwait(false);
bytesRead += secondRead;
this.Position += secondRead;
}
}
return bytesRead;
}
finally
{
this.shouldSeek = true;
}
}
/// <summary>
/// Reads a block of bytes from the wrapped stream asynchronously and writes the data to the SubStream buffer.
/// </summary>
/// <param name="buffer">When this method returns, the substream read buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read.</param>
/// <param name="cancellationToken">An object of type <see cref="CancellationToken"/> that propagates notification that operation should be canceled.</param>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the substream has been reached.</returns>
/// <remarks>
/// This method will allow only one read request to the underlying wrapped stream at a time,
/// while concurrent requests will be queued up by effect of the shared semaphore mutex.
/// The caller is responsible for adjusting the substream position after a successful read.
/// </remarks>
private async Task<int> ReadAsyncHelper(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await this.Mutex.WaitAsync(cancellationToken).ConfigureAwait(false);
int result = 0;
try
{
this.CheckDisposed();
// Check if read is out of range and adjust to read only up to the substream bounds.
count = this.CheckAdjustReadCount(count, offset, buffer.Length);
// Only seek if wrapped stream is misaligned with the substream position.
if (this.wrappedStream.Position != this.streamBeginIndex + this.Position)
{
this.wrappedStream.Seek(this.streamBeginIndex + this.Position, SeekOrigin.Begin);
}
result = await this.wrappedStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
}
finally
{
this.Mutex.Release();
}
return result;
}
public override int Read(byte[] buffer, int offset, int count)
{
return this.ReadAsync(buffer, offset, count).Result;
}
/// <summary>
/// Sets the position within the current substream.
/// This operation does not perform a seek on the wrapped stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type System.IO.SeekOrigin indicating the reference point used to obtain the new position.</param>
/// <returns>The new position within the current substream.</returns>
/// <exception cref="NotSupportedException">Thrown if using the unsupported <paramref name="origin"/> SeekOrigin.End </exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="offset"/> is invalid for SeekOrigin.</exception>
public override long Seek(long offset, SeekOrigin origin)
{
this.CheckDisposed();
long startIndex;
// Map offset to the specified SeekOrigin of the substream.
switch (origin)
{
case SeekOrigin.Begin:
startIndex = 0;
break;
case SeekOrigin.Current:
startIndex = this.Position;
break;
case SeekOrigin.End:
throw new NotSupportedException();
default:
throw new ArgumentOutOfRangeException();
}
this.Position = startIndex + offset;
return this.Position;
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
private int CheckAdjustReadCount(int count, int offset, int bufferLength)
{
if (offset < 0 || count < 0 || offset + count > bufferLength)
{
throw new ArgumentOutOfRangeException();
}
long currentPos = this.streamBeginIndex + this.Position;
long endPos = this.streamBeginIndex + this.substreamLength;
if (currentPos + count > endPos)
{
return (int)(endPos - currentPos);
}
else
{
return count;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Dynamic
{
public abstract partial class BinaryOperationBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected BinaryOperationBinder(System.Linq.Expressions.ExpressionType operation) { }
public System.Linq.Expressions.ExpressionType Operation { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject FallbackBinaryOperation(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject arg) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackBinaryOperation(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject arg, System.Dynamic.DynamicMetaObject errorSuggestion);
}
public abstract partial class BindingRestrictions
{
internal BindingRestrictions() { }
public static readonly System.Dynamic.BindingRestrictions Empty;
public static System.Dynamic.BindingRestrictions Combine(System.Collections.Generic.IList<System.Dynamic.DynamicMetaObject> contributingObjects) { throw null; }
public static System.Dynamic.BindingRestrictions GetExpressionRestriction(System.Linq.Expressions.Expression expression) { throw null; }
public static System.Dynamic.BindingRestrictions GetInstanceRestriction(System.Linq.Expressions.Expression expression, object instance) { throw null; }
public static System.Dynamic.BindingRestrictions GetTypeRestriction(System.Linq.Expressions.Expression expression, System.Type type) { throw null; }
public System.Dynamic.BindingRestrictions Merge(System.Dynamic.BindingRestrictions restrictions) { throw null; }
public System.Linq.Expressions.Expression ToExpression() { throw null; }
}
public sealed partial class CallInfo
{
public CallInfo(int argCount, System.Collections.Generic.IEnumerable<string> argNames) { }
public CallInfo(int argCount, params string[] argNames) { }
public int ArgumentCount { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<string> ArgumentNames { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
}
public abstract partial class ConvertBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected ConvertBinder(System.Type type, bool @explicit) { }
public bool Explicit { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public System.Type Type { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject FallbackConvert(System.Dynamic.DynamicMetaObject target) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackConvert(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject errorSuggestion);
}
public abstract partial class CreateInstanceBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected CreateInstanceBinder(System.Dynamic.CallInfo callInfo) { }
public System.Dynamic.CallInfo CallInfo { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject FallbackCreateInstance(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackCreateInstance(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args, System.Dynamic.DynamicMetaObject errorSuggestion);
}
public abstract partial class DeleteIndexBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected DeleteIndexBinder(System.Dynamic.CallInfo callInfo) { }
public System.Dynamic.CallInfo CallInfo { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject FallbackDeleteIndex(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] indexes) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackDeleteIndex(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] indexes, System.Dynamic.DynamicMetaObject errorSuggestion);
}
public abstract partial class DeleteMemberBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected DeleteMemberBinder(string name, bool ignoreCase) { }
public bool IgnoreCase { get { throw null; } }
public string Name { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject FallbackDeleteMember(System.Dynamic.DynamicMetaObject target) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackDeleteMember(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject errorSuggestion);
}
public partial class DynamicMetaObject
{
public static readonly System.Dynamic.DynamicMetaObject[] EmptyMetaObjects;
public DynamicMetaObject(System.Linq.Expressions.Expression expression, System.Dynamic.BindingRestrictions restrictions) { }
public DynamicMetaObject(System.Linq.Expressions.Expression expression, System.Dynamic.BindingRestrictions restrictions, object value) { }
public System.Linq.Expressions.Expression Expression { get { throw null; } }
public bool HasValue { get { throw null; } }
public System.Type LimitType { get { throw null; } }
public System.Dynamic.BindingRestrictions Restrictions { get { throw null; } }
public System.Type RuntimeType { get { throw null; } }
public object Value { get { throw null; } }
public virtual System.Dynamic.DynamicMetaObject BindBinaryOperation(System.Dynamic.BinaryOperationBinder binder, System.Dynamic.DynamicMetaObject arg) { throw null; }
public virtual System.Dynamic.DynamicMetaObject BindConvert(System.Dynamic.ConvertBinder binder) { throw null; }
public virtual System.Dynamic.DynamicMetaObject BindCreateInstance(System.Dynamic.CreateInstanceBinder binder, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public virtual System.Dynamic.DynamicMetaObject BindDeleteIndex(System.Dynamic.DeleteIndexBinder binder, System.Dynamic.DynamicMetaObject[] indexes) { throw null; }
public virtual System.Dynamic.DynamicMetaObject BindDeleteMember(System.Dynamic.DeleteMemberBinder binder) { throw null; }
public virtual System.Dynamic.DynamicMetaObject BindGetIndex(System.Dynamic.GetIndexBinder binder, System.Dynamic.DynamicMetaObject[] indexes) { throw null; }
public virtual System.Dynamic.DynamicMetaObject BindGetMember(System.Dynamic.GetMemberBinder binder) { throw null; }
public virtual System.Dynamic.DynamicMetaObject BindInvoke(System.Dynamic.InvokeBinder binder, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public virtual System.Dynamic.DynamicMetaObject BindInvokeMember(System.Dynamic.InvokeMemberBinder binder, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public virtual System.Dynamic.DynamicMetaObject BindSetIndex(System.Dynamic.SetIndexBinder binder, System.Dynamic.DynamicMetaObject[] indexes, System.Dynamic.DynamicMetaObject value) { throw null; }
public virtual System.Dynamic.DynamicMetaObject BindSetMember(System.Dynamic.SetMemberBinder binder, System.Dynamic.DynamicMetaObject value) { throw null; }
public virtual System.Dynamic.DynamicMetaObject BindUnaryOperation(System.Dynamic.UnaryOperationBinder binder) { throw null; }
public static System.Dynamic.DynamicMetaObject Create(object value, System.Linq.Expressions.Expression expression) { throw null; }
public virtual System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames() { throw null; }
}
public abstract partial class DynamicMetaObjectBinder : System.Runtime.CompilerServices.CallSiteBinder
{
protected DynamicMetaObjectBinder() { }
public virtual System.Type ReturnType { get { throw null; } }
public abstract System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args);
public sealed override System.Linq.Expressions.Expression Bind(object[] args, System.Collections.ObjectModel.ReadOnlyCollection<System.Linq.Expressions.ParameterExpression> parameters, System.Linq.Expressions.LabelTarget returnLabel) { throw null; }
public System.Dynamic.DynamicMetaObject Defer(System.Dynamic.DynamicMetaObject target, params System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject Defer(params System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Linq.Expressions.Expression GetUpdateExpression(System.Type type) { throw null; }
}
public partial class DynamicObject : System.Dynamic.IDynamicMetaObjectProvider
{
protected DynamicObject() { }
public virtual System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames() { throw null; }
public virtual System.Dynamic.DynamicMetaObject GetMetaObject(System.Linq.Expressions.Expression parameter) { throw null; }
public virtual bool TryBinaryOperation(System.Dynamic.BinaryOperationBinder binder, object arg, out object result) { result = default(object); throw null; }
public virtual bool TryConvert(System.Dynamic.ConvertBinder binder, out object result) { result = default(object); throw null; }
public virtual bool TryCreateInstance(System.Dynamic.CreateInstanceBinder binder, object[] args, out object result) { result = default(object); throw null; }
public virtual bool TryDeleteIndex(System.Dynamic.DeleteIndexBinder binder, object[] indexes) { throw null; }
public virtual bool TryDeleteMember(System.Dynamic.DeleteMemberBinder binder) { throw null; }
public virtual bool TryGetIndex(System.Dynamic.GetIndexBinder binder, object[] indexes, out object result) { result = default(object); throw null; }
public virtual bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result) { result = default(object); throw null; }
public virtual bool TryInvoke(System.Dynamic.InvokeBinder binder, object[] args, out object result) { result = default(object); throw null; }
public virtual bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result) { result = default(object); throw null; }
public virtual bool TrySetIndex(System.Dynamic.SetIndexBinder binder, object[] indexes, object value) { throw null; }
public virtual bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value) { throw null; }
public virtual bool TryUnaryOperation(System.Dynamic.UnaryOperationBinder binder, out object result) { result = default(object); throw null; }
}
public sealed partial class ExpandoObject : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, object>>, System.Collections.Generic.IDictionary<string, object>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, object>>, System.Collections.IEnumerable, System.ComponentModel.INotifyPropertyChanged, System.Dynamic.IDynamicMetaObjectProvider
{
public ExpandoObject() { }
int System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Count { get { throw null; } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.IsReadOnly { get { throw null; } }
object System.Collections.Generic.IDictionary<System.String,System.Object>.this[string key] { get { throw null; } set { } }
System.Collections.Generic.ICollection<string> System.Collections.Generic.IDictionary<System.String,System.Object>.Keys { get { throw null; } }
System.Collections.Generic.ICollection<object> System.Collections.Generic.IDictionary<System.String,System.Object>.Values { get { throw null; } }
event System.ComponentModel.PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Add(System.Collections.Generic.KeyValuePair<string, object> item) { }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Clear() { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Contains(System.Collections.Generic.KeyValuePair<string, object> item) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.CopyTo(System.Collections.Generic.KeyValuePair<string, object>[] array, int arrayIndex) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Remove(System.Collections.Generic.KeyValuePair<string, object> item) { throw null; }
void System.Collections.Generic.IDictionary<System.String,System.Object>.Add(string key, object value) { }
bool System.Collections.Generic.IDictionary<System.String,System.Object>.ContainsKey(string key) { throw null; }
bool System.Collections.Generic.IDictionary<System.String,System.Object>.Remove(string key) { throw null; }
bool System.Collections.Generic.IDictionary<System.String,System.Object>.TryGetValue(string key, out object value) { value = default(object); throw null; }
System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, object>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
System.Dynamic.DynamicMetaObject System.Dynamic.IDynamicMetaObjectProvider.GetMetaObject(System.Linq.Expressions.Expression parameter) { throw null; }
}
public abstract partial class GetIndexBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected GetIndexBinder(System.Dynamic.CallInfo callInfo) { }
public System.Dynamic.CallInfo CallInfo { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject FallbackGetIndex(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] indexes) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackGetIndex(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] indexes, System.Dynamic.DynamicMetaObject errorSuggestion);
}
public abstract partial class GetMemberBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected GetMemberBinder(string name, bool ignoreCase) { }
public bool IgnoreCase { get { throw null; } }
public string Name { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject FallbackGetMember(System.Dynamic.DynamicMetaObject target) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackGetMember(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject errorSuggestion);
}
public partial interface IDynamicMetaObjectProvider
{
System.Dynamic.DynamicMetaObject GetMetaObject(System.Linq.Expressions.Expression parameter);
}
public partial interface IInvokeOnGetBinder
{
bool InvokeOnGet { get; }
}
public abstract partial class InvokeBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected InvokeBinder(System.Dynamic.CallInfo callInfo) { }
public System.Dynamic.CallInfo CallInfo { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject FallbackInvoke(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackInvoke(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args, System.Dynamic.DynamicMetaObject errorSuggestion);
}
public abstract partial class InvokeMemberBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected InvokeMemberBinder(string name, bool ignoreCase, System.Dynamic.CallInfo callInfo) { }
public System.Dynamic.CallInfo CallInfo { get { throw null; } }
public bool IgnoreCase { get { throw null; } }
public string Name { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackInvoke(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args, System.Dynamic.DynamicMetaObject errorSuggestion);
public System.Dynamic.DynamicMetaObject FallbackInvokeMember(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackInvokeMember(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args, System.Dynamic.DynamicMetaObject errorSuggestion);
}
public abstract partial class SetIndexBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected SetIndexBinder(System.Dynamic.CallInfo callInfo) { }
public System.Dynamic.CallInfo CallInfo { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject FallbackSetIndex(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] indexes, System.Dynamic.DynamicMetaObject value) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackSetIndex(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] indexes, System.Dynamic.DynamicMetaObject value, System.Dynamic.DynamicMetaObject errorSuggestion);
}
public abstract partial class SetMemberBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected SetMemberBinder(string name, bool ignoreCase) { }
public bool IgnoreCase { get { throw null; } }
public string Name { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject FallbackSetMember(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject value) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackSetMember(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject value, System.Dynamic.DynamicMetaObject errorSuggestion);
}
public abstract partial class UnaryOperationBinder : System.Dynamic.DynamicMetaObjectBinder
{
protected UnaryOperationBinder(System.Linq.Expressions.ExpressionType operation) { }
public System.Linq.Expressions.ExpressionType Operation { get { throw null; } }
public sealed override System.Type ReturnType { get { throw null; } }
public sealed override System.Dynamic.DynamicMetaObject Bind(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject[] args) { throw null; }
public System.Dynamic.DynamicMetaObject FallbackUnaryOperation(System.Dynamic.DynamicMetaObject target) { throw null; }
public abstract System.Dynamic.DynamicMetaObject FallbackUnaryOperation(System.Dynamic.DynamicMetaObject target, System.Dynamic.DynamicMetaObject errorSuggestion);
}
}
| |
/*
* 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 rds-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Container for the parameters to the ModifyDBCluster operation.
/// Modify a setting for an Amazon Aurora DB cluster. You can change one or more database
/// configuration parameters by specifying these parameters and the new values in the
/// request. For more information on Amazon Aurora, see <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Aurora.html">Aurora
/// on Amazon RDS</a> in the <i>Amazon RDS User Guide.</i>
/// </summary>
public partial class ModifyDBClusterRequest : AmazonRDSRequest
{
private bool? _applyImmediately;
private int? _backupRetentionPeriod;
private string _dbClusterIdentifier;
private string _dbClusterParameterGroupName;
private string _masterUserPassword;
private string _newDBClusterIdentifier;
private string _optionGroupName;
private int? _port;
private string _preferredBackupWindow;
private string _preferredMaintenanceWindow;
private List<string> _vpcSecurityGroupIds = new List<string>();
/// <summary>
/// Gets and sets the property ApplyImmediately.
/// <para>
/// A value that specifies whether the modifications in this request and any pending modifications
/// are asynchronously applied as soon as possible, regardless of the <code>PreferredMaintenanceWindow</code>
/// setting for the DB cluster.
/// </para>
///
/// <para>
/// If this parameter is set to <code>false</code>, changes to the DB cluster are applied
/// during the next maintenance window.
/// </para>
///
/// <para>
/// Default: <code>false</code>
/// </para>
/// </summary>
public bool ApplyImmediately
{
get { return this._applyImmediately.GetValueOrDefault(); }
set { this._applyImmediately = value; }
}
// Check to see if ApplyImmediately property is set
internal bool IsSetApplyImmediately()
{
return this._applyImmediately.HasValue;
}
/// <summary>
/// Gets and sets the property BackupRetentionPeriod.
/// <para>
/// The number of days for which automated backups are retained. You must specify a minimum
/// value of 1.
/// </para>
///
/// <para>
/// Default: 1
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be a value from 1 to 35</li> </ul>
/// </summary>
public int BackupRetentionPeriod
{
get { return this._backupRetentionPeriod.GetValueOrDefault(); }
set { this._backupRetentionPeriod = value; }
}
// Check to see if BackupRetentionPeriod property is set
internal bool IsSetBackupRetentionPeriod()
{
return this._backupRetentionPeriod.HasValue;
}
/// <summary>
/// Gets and sets the property DBClusterIdentifier.
/// <para>
/// The DB cluster identifier for the cluster being modified. This parameter is not case-sensitive.
///
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be the identifier for an existing DB cluster.</li> <li>Must contain
/// from 1 to 63 alphanumeric characters or hyphens.</li> <li>First character must be
/// a letter.</li> <li>Cannot end with a hyphen or contain two consecutive hyphens.</li>
/// </ul>
/// </summary>
public string DBClusterIdentifier
{
get { return this._dbClusterIdentifier; }
set { this._dbClusterIdentifier = value; }
}
// Check to see if DBClusterIdentifier property is set
internal bool IsSetDBClusterIdentifier()
{
return this._dbClusterIdentifier != null;
}
/// <summary>
/// Gets and sets the property DBClusterParameterGroupName.
/// <para>
/// The name of the DB cluster parameter group to use for the DB cluster.
/// </para>
/// </summary>
public string DBClusterParameterGroupName
{
get { return this._dbClusterParameterGroupName; }
set { this._dbClusterParameterGroupName = value; }
}
// Check to see if DBClusterParameterGroupName property is set
internal bool IsSetDBClusterParameterGroupName()
{
return this._dbClusterParameterGroupName != null;
}
/// <summary>
/// Gets and sets the property MasterUserPassword.
/// <para>
/// The new password for the master database user. This password can contain any printable
/// ASCII character except "/", """, or "@".
/// </para>
///
/// <para>
/// Constraints: Must contain from 8 to 41 characters.
/// </para>
/// </summary>
public string MasterUserPassword
{
get { return this._masterUserPassword; }
set { this._masterUserPassword = value; }
}
// Check to see if MasterUserPassword property is set
internal bool IsSetMasterUserPassword()
{
return this._masterUserPassword != null;
}
/// <summary>
/// Gets and sets the property NewDBClusterIdentifier.
/// <para>
/// The new DB cluster identifier for the DB cluster when renaming a DB cluster. This
/// value is stored as a lowercase string.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must contain from 1 to 63 alphanumeric characters or hyphens</li> <li>First
/// character must be a letter</li> <li>Cannot end with a hyphen or contain two consecutive
/// hyphens</li> </ul>
/// <para>
/// Example: <code>my-cluster2</code>
/// </para>
/// </summary>
public string NewDBClusterIdentifier
{
get { return this._newDBClusterIdentifier; }
set { this._newDBClusterIdentifier = value; }
}
// Check to see if NewDBClusterIdentifier property is set
internal bool IsSetNewDBClusterIdentifier()
{
return this._newDBClusterIdentifier != null;
}
/// <summary>
/// Gets and sets the property OptionGroupName.
/// <para>
/// A value that indicates that the DB cluster should be associated with the specified
/// option group. Changing this parameter does not result in an outage except in the following
/// case, and the change is applied during the next maintenance window unless the <code>ApplyImmediately</code>
/// parameter is set to <code>true</code> for this request. If the parameter change results
/// in an option group that enables OEM, this change can cause a brief (sub-second) period
/// during which new connections are rejected but existing connections are not interrupted.
///
/// </para>
///
/// <para>
/// Permanent options cannot be removed from an option group. The option group cannot
/// be removed from a DB cluster once it is associated with a DB cluster.
/// </para>
/// </summary>
public string OptionGroupName
{
get { return this._optionGroupName; }
set { this._optionGroupName = value; }
}
// Check to see if OptionGroupName property is set
internal bool IsSetOptionGroupName()
{
return this._optionGroupName != null;
}
/// <summary>
/// Gets and sets the property Port.
/// <para>
/// The port number on which the DB cluster accepts connections.
/// </para>
///
/// <para>
/// Constraints: Value must be <code>1150-65535</code>
/// </para>
///
/// <para>
/// Default: The same port as the original DB cluster.
/// </para>
/// </summary>
public int Port
{
get { return this._port.GetValueOrDefault(); }
set { this._port = value; }
}
// Check to see if Port property is set
internal bool IsSetPort()
{
return this._port.HasValue;
}
/// <summary>
/// Gets and sets the property PreferredBackupWindow.
/// <para>
/// The daily time range during which automated backups are created if automated backups
/// are enabled, using the <code>BackupRetentionPeriod</code> parameter.
/// </para>
///
/// <para>
/// Default: A 30-minute window selected at random from an 8-hour block of time per region.
/// To see the time blocks available, see <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/AdjustingTheMaintenanceWindow.html">
/// Adjusting the Preferred Maintenance Window</a> in the <i>Amazon RDS User Guide.</i>
///
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be in the format <code>hh24:mi-hh24:mi</code>.</li> <li>Times should
/// be in Universal Coordinated Time (UTC).</li> <li>Must not conflict with the preferred
/// maintenance window.</li> <li>Must be at least 30 minutes.</li> </ul>
/// </summary>
public string PreferredBackupWindow
{
get { return this._preferredBackupWindow; }
set { this._preferredBackupWindow = value; }
}
// Check to see if PreferredBackupWindow property is set
internal bool IsSetPreferredBackupWindow()
{
return this._preferredBackupWindow != null;
}
/// <summary>
/// Gets and sets the property PreferredMaintenanceWindow.
/// <para>
/// The weekly time range during which system maintenance can occur, in Universal Coordinated
/// Time (UTC).
/// </para>
///
/// <para>
/// Format: <code>ddd:hh24:mi-ddd:hh24:mi</code>
/// </para>
///
/// <para>
/// Default: A 30-minute window selected at random from an 8-hour block of time per region,
/// occurring on a random day of the week. To see the time blocks available, see <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/AdjustingTheMaintenanceWindow.html">
/// Adjusting the Preferred Maintenance Window</a> in the <i>Amazon RDS User Guide.</i>
///
/// </para>
///
/// <para>
/// Valid Days: Mon, Tue, Wed, Thu, Fri, Sat, Sun
/// </para>
///
/// <para>
/// Constraints: Minimum 30-minute window.
/// </para>
/// </summary>
public string PreferredMaintenanceWindow
{
get { return this._preferredMaintenanceWindow; }
set { this._preferredMaintenanceWindow = value; }
}
// Check to see if PreferredMaintenanceWindow property is set
internal bool IsSetPreferredMaintenanceWindow()
{
return this._preferredMaintenanceWindow != null;
}
/// <summary>
/// Gets and sets the property VpcSecurityGroupIds.
/// <para>
/// A lst of VPC security groups that the DB cluster will belong to.
/// </para>
/// </summary>
public List<string> VpcSecurityGroupIds
{
get { return this._vpcSecurityGroupIds; }
set { this._vpcSecurityGroupIds = value; }
}
// Check to see if VpcSecurityGroupIds property is set
internal bool IsSetVpcSecurityGroupIds()
{
return this._vpcSecurityGroupIds != null && this._vpcSecurityGroupIds.Count > 0;
}
}
}
| |
// 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 Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class LoopHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override IHighlighter CreateHighlighter()
{
return new LoopHighlighter();
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample1_1()
{
Test(
@"class C {
void M() {
{|Cursor:[|while|]|} (true) {
if (x) {
[|break|];
}
else {
[|continue|];
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample1_2()
{
Test(
@"class C {
void M() {
[|while|] (true) {
if (x) {
{|Cursor:[|break|]|};
}
else {
[|continue|];
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample1_3()
{
Test(
@"class C {
void M() {
[|while|] (true) {
if (x) {
[|break|];
}
else {
{|Cursor:[|continue|]|};
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample2_1()
{
Test(
@"class C {
void M() {
{|Cursor:[|do|]|} {
if (x) {
[|break|];
}
else {
[|continue|];
}
}
[|while|] (true);
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample2_2()
{
Test(
@"class C {
void M() {
[|do|] {
if (x) {
{|Cursor:[|break|]|};
}
else {
[|continue|];
}
}
[|while|] (true);
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample2_3()
{
Test(
@"class C {
void M() {
[|do|] {
if (x) {
[|break|];
}
else {
{|Cursor:[|continue|]|};
}
}
[|while|] (true);
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample2_4()
{
Test(
@"class C {
void M() {
[|do|] {
if (x) {
[|break|];
}
else {
[|continue|];
}
}
{|Cursor:[|while|]|} (true);
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample2_5()
{
Test(
@"class C {
void M() {
do {
if (x) {
break;
}
else {
continue;
}
}
while {|Cursor:(true)|};
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample2_6()
{
Test(
@"class C {
void M() {
[|do|] {
if (x) {
[|break|];
}
else {
[|continue|];
}
}
[|while|] (true);{|Cursor:|}
}
}");
}
private const string SpecExample3 = @"for (int i = 0; i < 10; i++) {
if (x) {
break;
}
else {
continue;
}
}";
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample3_1()
{
Test(
@"class C {
void M() {
{|Cursor:[|for|]|} (int i = 0; i < 10; i++) {
if (x) {
[|break|];
}
else {
[|continue|];
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample3_2()
{
Test(
@"class C {
void M() {
[|for|] (int i = 0; i < 10; i++) {
if (x) {
{|Cursor:[|break|];|}
}
else {
[|continue|];
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample3_3()
{
Test(
@"class C {
void M() {
[|for|] (int i = 0; i < 10; i++) {
if (x) {
[|break|];
}
else {
{|Cursor:[|continue|];|}
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample4_1()
{
Test(
@"class C {
void M() {
{|Cursor:[|foreach|]|} (var a in x) {
if (x) {
[|break|];
}
else {
[|continue|];
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample4_2()
{
Test(
@"class C {
void M() {
[|foreach|] (var a in x) {
if (x) {
{|Cursor:[|break|];|}
}
else {
[|continue|];
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestExample4_3()
{
Test(
@"class C {
void M() {
[|foreach|] (var a in x) {
if (x) {
[|break|];
}
else {
{|Cursor:[|continue|];|}
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample1_1()
{
Test(
@"class C {
void M() {
{|Cursor:[|foreach|]|} (var a in x) {
if (a) {
[|break|];
}
else {
switch (b) {
case 0:
while (true) {
do {
break;
}
while (false);
break;
}
break;
}
}
for (int i = 0; i < 10; i++) {
break;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample1_2()
{
Test(
@"class C {
void M() {
[|foreach|] (var a in x) {
if (a) {
{|Cursor:[|break|];|}
}
else {
switch (b) {
case 0:
while (true) {
do {
break;
}
while (false);
break;
}
break;
}
}
for (int i = 0; i < 10; i++) {
break;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample1_3()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
break;
}
else {
switch (b) {
case 0:
while (true) {
{|Cursor:[|do|]|} {
[|break|];
}
[|while|] (false);
break;
}
break;
}
}
for (int i = 0; i < 10; i++) {
break;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample1_4()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
break;
}
else {
switch (b) {
case 0:
while (true) {
[|do|] {
{|Cursor:[|break|];|}
}
[|while|] (false);
break;
}
break;
}
}
for (int i = 0; i < 10; i++) {
break;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample1_5()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
break;
}
else {
switch (b) {
case 0:
while (true) {
[|do|] {
[|break|];
}
{|Cursor:[|while|]|} (false);
break;
}
break;
}
}
for (int i = 0; i < 10; i++) {
break;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample1_6()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
break;
}
else {
switch (b) {
case 0:
while (true) {
[|do|] {
[|break|];
}
[|while|] (false);{|Cursor:|}
break;
}
break;
}
}
for (int i = 0; i < 10; i++) {
break;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample1_7()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
break;
}
else {
switch (b) {
case 0:
{|Cursor:[|while|]|} (true) {
do {
break;
}
while (false);
[|break|];
}
break;
}
}
for (int i = 0; i < 10; i++) {
break;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample1_8()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
break;
}
else {
switch (b) {
case 0:
[|while|] (true) {
do {
break;
}
while (false);
{|Cursor:[|break|];|}
}
break;
}
}
for (int i = 0; i < 10; i++) {
break;
}
}
}
}
");
}
// TestNestedExample1 9-13 are in SwitchStatementHighlighterTests.cs
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample1_14()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
break;
}
else {
switch (b) {
case 0:
while (true) {
do {
break;
}
while (false);
break;
}
break;
}
}
{|Cursor:[|for|]|} (int i = 0; i < 10; i++) {
[|break|];
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample1_15()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
break;
}
else {
switch (b) {
case 0:
while (true) {
do {
break;
}
while (false);
break;
}
break;
}
}
[|for|] (int i = 0; i < 10; i++) {
{|Cursor:[|break|];|}
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample2_1()
{
Test(
@"class C {
void M() {
{|Cursor:[|foreach|]|} (var a in x) {
if (a) {
[|continue|];
}
else {
while (true) {
do {
continue;
}
while (false);
continue;
}
}
for (int i = 0; i < 10; i++) {
continue;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample2_2()
{
Test(
@"class C {
void M() {
[|foreach|] (var a in x) {
if (a) {
{|Cursor:[|continue|];|}
}
else {
while (true) {
do {
continue;
}
while (false);
continue;
}
}
for (int i = 0; i < 10; i++) {
continue;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample2_3()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
continue;
}
else {
while (true) {
{|Cursor:[|do|]|} {
[|continue|];
}
[|while|] (false);
continue;
}
}
for (int i = 0; i < 10; i++) {
continue;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample2_4()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
continue;
}
else {
while (true) {
[|do|] {
{|Cursor:[|continue|];|}
}
[|while|] (false);
continue;
}
}
for (int i = 0; i < 10; i++) {
continue;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample2_5()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
continue;
}
else {
while (true) {
[|do|] {
[|continue|];
}
{|Cursor:[|while|]|} (false);
continue;
}
}
for (int i = 0; i < 10; i++) {
continue;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample2_6()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
continue;
}
else {
while (true) {
do {
continue;
}
while {|Cursor:(false)|};
continue;
}
}
for (int i = 0; i < 10; i++) {
continue;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample2_7()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
continue;
}
else {
while (true) {
[|do|] {
[|continue|];
}
[|while|] (false);{|Cursor:|}
continue;
}
}
for (int i = 0; i < 10; i++) {
continue;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample2_8()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
continue;
}
else {
{|Cursor:[|while|]|} (true) {
do {
continue;
}
while (false);
[|continue|];
}
}
for (int i = 0; i < 10; i++) {
continue;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample2_9()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
continue;
}
else {
[|while|] (true) {
do {
continue;
}
while (false);
{|Cursor:[|continue|];|}
}
}
for (int i = 0; i < 10; i++) {
continue;
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample2_10()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
continue;
}
else {
while (true) {
do {
continue;
}
while (false);
continue;
}
}
{|Cursor:[|for|]|} (int i = 0; i < 10; i++) {
[|continue|];
}
}
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public void TestNestedExample2_11()
{
Test(
@"class C {
void M() {
foreach (var a in x) {
if (a) {
continue;
}
else {
while (true) {
do {
continue;
}
while (false);
continue;
}
}
[|for|] (int i = 0; i < 10; i++) {
{|Cursor:[|continue|];|}
}
}
}
}
");
}
}
}
| |
namespace FindEmptyDirs {
partial class Form1 {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.buttonFindRoot = new System.Windows.Forms.Button();
this.listBoxResult = new System.Windows.Forms.ListBox();
this.label1 = new System.Windows.Forms.Label();
this.textBoxRoot = new System.Windows.Forms.TextBox();
this.buttonFind = new System.Windows.Forms.Button();
this.textBoxExcludes = new System.Windows.Forms.TextBox();
this.labelExcludes = new System.Windows.Forms.Label();
this.labelExcludesExample = new System.Windows.Forms.Label();
this.labelDirsFound = new System.Windows.Forms.Label();
this.textBoxDirsFound = new System.Windows.Forms.TextBox();
this.buttonDeleteSelectedDirs = new System.Windows.Forms.Button();
this.buttonSelectAll = new System.Windows.Forms.Button();
this.buttonUnSelectAll = new System.Windows.Forms.Button();
this.buttonAbout = new System.Windows.Forms.Button();
this.listBoxErrors = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// buttonFindRoot
//
this.buttonFindRoot.Location = new System.Drawing.Point(795, 32);
this.buttonFindRoot.Name = "buttonFindRoot";
this.buttonFindRoot.Size = new System.Drawing.Size(75, 23);
this.buttonFindRoot.TabIndex = 4;
this.buttonFindRoot.Text = "Find &Root";
this.buttonFindRoot.UseVisualStyleBackColor = true;
this.buttonFindRoot.Click += new System.EventHandler(this.buttonFindRoot_Click);
//
// listBoxResult
//
this.listBoxResult.FormattingEnabled = true;
this.listBoxResult.Location = new System.Drawing.Point(12, 62);
this.listBoxResult.Name = "listBoxResult";
this.listBoxResult.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.listBoxResult.Size = new System.Drawing.Size(858, 368);
this.listBoxResult.TabIndex = 5;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(9, 10);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(33, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Root:";
//
// textBoxRoot
//
this.textBoxRoot.Location = new System.Drawing.Point(48, 7);
this.textBoxRoot.Name = "textBoxRoot";
this.textBoxRoot.Size = new System.Drawing.Size(822, 20);
this.textBoxRoot.TabIndex = 0;
//
// buttonFind
//
this.buttonFind.Location = new System.Drawing.Point(12, 33);
this.buttonFind.Name = "buttonFind";
this.buttonFind.Size = new System.Drawing.Size(75, 23);
this.buttonFind.TabIndex = 1;
this.buttonFind.Text = "&Find";
this.buttonFind.UseVisualStyleBackColor = true;
this.buttonFind.Click += new System.EventHandler(this.buttonFind_Click);
//
// textBoxExcludes
//
this.textBoxExcludes.Location = new System.Drawing.Point(216, 35);
this.textBoxExcludes.Name = "textBoxExcludes";
this.textBoxExcludes.Size = new System.Drawing.Size(100, 20);
this.textBoxExcludes.TabIndex = 2;
//
// labelExcludes
//
this.labelExcludes.AutoSize = true;
this.labelExcludes.Location = new System.Drawing.Point(154, 38);
this.labelExcludes.Name = "labelExcludes";
this.labelExcludes.Size = new System.Drawing.Size(56, 13);
this.labelExcludes.TabIndex = 6;
this.labelExcludes.Text = "Excludes: ";
//
// labelExcludesExample
//
this.labelExcludesExample.AutoSize = true;
this.labelExcludesExample.Location = new System.Drawing.Point(322, 38);
this.labelExcludesExample.Name = "labelExcludesExample";
this.labelExcludesExample.Size = new System.Drawing.Size(80, 13);
this.labelExcludesExample.TabIndex = 7;
this.labelExcludesExample.Text = "e.g.: svn secret";
//
// labelDirsFound
//
this.labelDirsFound.AutoSize = true;
this.labelDirsFound.Location = new System.Drawing.Point(497, 38);
this.labelDirsFound.Name = "labelDirsFound";
this.labelDirsFound.Size = new System.Drawing.Size(58, 13);
this.labelDirsFound.TabIndex = 8;
this.labelDirsFound.Text = "Dirs found:";
//
// textBoxDirsFound
//
this.textBoxDirsFound.Enabled = false;
this.textBoxDirsFound.Location = new System.Drawing.Point(561, 35);
this.textBoxDirsFound.Name = "textBoxDirsFound";
this.textBoxDirsFound.Size = new System.Drawing.Size(100, 20);
this.textBoxDirsFound.TabIndex = 3;
//
// buttonDeleteSelectedDirs
//
this.buttonDeleteSelectedDirs.Location = new System.Drawing.Point(12, 434);
this.buttonDeleteSelectedDirs.Name = "buttonDeleteSelectedDirs";
this.buttonDeleteSelectedDirs.Size = new System.Drawing.Size(139, 23);
this.buttonDeleteSelectedDirs.TabIndex = 6;
this.buttonDeleteSelectedDirs.Text = "&Delete Selected Dirs";
this.buttonDeleteSelectedDirs.UseVisualStyleBackColor = true;
this.buttonDeleteSelectedDirs.Click += new System.EventHandler(this.buttonDeleteSelectedDirs_Click);
//
// buttonSelectAll
//
this.buttonSelectAll.Location = new System.Drawing.Point(216, 434);
this.buttonSelectAll.Name = "buttonSelectAll";
this.buttonSelectAll.Size = new System.Drawing.Size(75, 23);
this.buttonSelectAll.TabIndex = 7;
this.buttonSelectAll.Text = "&Select All";
this.buttonSelectAll.UseVisualStyleBackColor = true;
this.buttonSelectAll.Click += new System.EventHandler(this.buttonSelectAll_Click);
//
// buttonUnSelectAll
//
this.buttonUnSelectAll.Location = new System.Drawing.Point(298, 434);
this.buttonUnSelectAll.Name = "buttonUnSelectAll";
this.buttonUnSelectAll.Size = new System.Drawing.Size(75, 23);
this.buttonUnSelectAll.TabIndex = 8;
this.buttonUnSelectAll.Text = "&UnSelect All";
this.buttonUnSelectAll.UseVisualStyleBackColor = true;
this.buttonUnSelectAll.Click += new System.EventHandler(this.buttonUnSelectAll_Click);
//
// buttonAbout
//
this.buttonAbout.Location = new System.Drawing.Point(795, 434);
this.buttonAbout.Name = "buttonAbout";
this.buttonAbout.Size = new System.Drawing.Size(75, 23);
this.buttonAbout.TabIndex = 9;
this.buttonAbout.Text = "&About";
this.buttonAbout.UseVisualStyleBackColor = true;
this.buttonAbout.Click += new System.EventHandler(this.buttonAbout_Click);
//
// listBoxErrors
//
this.listBoxErrors.Enabled = false;
this.listBoxErrors.FormattingEnabled = true;
this.listBoxErrors.Location = new System.Drawing.Point(12, 463);
this.listBoxErrors.Name = "listBoxErrors";
this.listBoxErrors.Size = new System.Drawing.Size(858, 108);
this.listBoxErrors.TabIndex = 10;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(882, 579);
this.Controls.Add(this.listBoxErrors);
this.Controls.Add(this.buttonAbout);
this.Controls.Add(this.buttonUnSelectAll);
this.Controls.Add(this.buttonSelectAll);
this.Controls.Add(this.buttonDeleteSelectedDirs);
this.Controls.Add(this.textBoxDirsFound);
this.Controls.Add(this.labelDirsFound);
this.Controls.Add(this.labelExcludesExample);
this.Controls.Add(this.labelExcludes);
this.Controls.Add(this.textBoxExcludes);
this.Controls.Add(this.buttonFind);
this.Controls.Add(this.textBoxRoot);
this.Controls.Add(this.label1);
this.Controls.Add(this.listBoxResult);
this.Controls.Add(this.buttonFindRoot);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Find Empty Directories 1.1 by Thomas Gassner";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button buttonFindRoot;
private System.Windows.Forms.ListBox listBoxResult;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBoxRoot;
private System.Windows.Forms.Button buttonFind;
private System.Windows.Forms.TextBox textBoxExcludes;
private System.Windows.Forms.Label labelExcludes;
private System.Windows.Forms.Label labelExcludesExample;
private System.Windows.Forms.Label labelDirsFound;
private System.Windows.Forms.TextBox textBoxDirsFound;
private System.Windows.Forms.Button buttonDeleteSelectedDirs;
private System.Windows.Forms.Button buttonSelectAll;
private System.Windows.Forms.Button buttonUnSelectAll;
private System.Windows.Forms.Button buttonAbout;
private System.Windows.Forms.ListBox listBoxErrors;
}
}
| |
/* ====================================================================
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 TestCases.DDF
{
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using NPOI.DDF;
using NPOI.Util;
using System.Configuration;
[TestFixture]
public class TestEscherContainerRecord
{
private static POIDataSamples _samples = POIDataSamples.GetDDFInstance();
private String ESCHER_DATA_PATH;
public TestEscherContainerRecord()
{
ESCHER_DATA_PATH = ConfigurationManager.AppSettings["escher.data.path"];
}
[Test]
public void TestFillFields()
{
IEscherRecordFactory f = new DefaultEscherRecordFactory();
byte[] data = HexRead.ReadFromString("0F 02 11 F1 00 00 00 00");
EscherRecord r = f.CreateRecord(data, 0);
r.FillFields(data, 0, f);
Assert.IsTrue(r is EscherContainerRecord);
Assert.AreEqual((short)0x020F, r.Options);
Assert.AreEqual(unchecked((short)0xF111), r.RecordId);
data = HexRead.ReadFromString("0F 02 11 F1 08 00 00 00" +
" 02 00 22 F2 00 00 00 00");
r = f.CreateRecord(data, 0);
r.FillFields(data, 0, f);
EscherRecord c = r.GetChild(0);
Assert.IsFalse(c is EscherContainerRecord);
Assert.AreEqual(unchecked((short)0x0002), c.Options);
Assert.AreEqual(unchecked((short)0xF222), c.RecordId);
}
[Test]
public void TestSerialize()
{
UnknownEscherRecord r = new UnknownEscherRecord();
r.Options=(short)0x123F;
r.RecordId=unchecked((short)0xF112);
byte[] data = new byte[8];
r.Serialize(0, data);
Assert.AreEqual("[3F, 12, 12, F1, 00, 00, 00, 00]", HexDump.ToHex(data));
EscherRecord childRecord = new UnknownEscherRecord();
childRecord.Options=unchecked((short)0x9999);
childRecord.RecordId=unchecked((short)0xFF01);
r.AddChildRecord(childRecord);
data = new byte[16];
r.Serialize(0, data);
Assert.AreEqual("[3F, 12, 12, F1, 08, 00, 00, 00, 99, 99, 01, FF, 00, 00, 00, 00]", HexDump.ToHex(data));
}
[Test]
public void TestToString()
{
EscherContainerRecord r = new EscherContainerRecord();
r.RecordId=EscherContainerRecord.SP_CONTAINER;
r.Options=(short)0x000F;
String nl = Environment.NewLine;
Assert.AreEqual("EscherContainerRecord (SpContainer):" + nl +
" isContainer: True" + nl +
" version: 0x000F" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF004" + nl +
" numchildren: 0" + nl
, r.ToString());
EscherOptRecord r2 = new EscherOptRecord();
// don't try to shoot in foot, please -- vlsergey
// r2.setOptions((short) 0x9876);
r2.RecordId=EscherOptRecord.RECORD_ID;
String expected;
r.AddChildRecord(r2);
expected = "EscherContainerRecord (SpContainer):" + nl +
" isContainer: True" + nl +
" version: 0x000F" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF004" + nl +
" numchildren: 1" + nl +
" children: " + nl +
" Child 0:" + nl +
" EscherOptRecord:" + nl +
" isContainer: False" + nl +
" version: 0x0003" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF00B" + nl +
" numchildren: 0" + nl +
" properties:" + nl +
" " + nl;
Assert.AreEqual(expected, r.ToString());
r.AddChildRecord(r2);
expected = "EscherContainerRecord (SpContainer):" + nl +
" isContainer: True" + nl +
" version: 0x000F" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF004" + nl +
" numchildren: 2" + nl +
" children: " + nl +
" Child 0:" + nl +
" EscherOptRecord:" + nl +
" isContainer: False" + nl +
" version: 0x0003" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF00B" + nl +
" numchildren: 0" + nl +
" properties:" + nl +
" " + nl +
" Child 1:" + nl +
" EscherOptRecord:" + nl +
" isContainer: False" + nl +
" version: 0x0003" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF00B" + nl +
" numchildren: 0" + nl +
" properties:" + nl +
" " + nl;
Assert.AreEqual(expected, r.ToString());
}
private class DummyEscherRecord : EscherRecord
{
public DummyEscherRecord() { }
public override int FillFields(byte[] data, int offset, IEscherRecordFactory recordFactory)
{ return 0; }
public override int Serialize(int offset, byte[] data, EscherSerializationListener listener)
{ return 0; }
public override int RecordSize { get { return 10; } }
public override String RecordName { get { return ""; } }
}
[Test]
public void TestRecordSize()
{
EscherContainerRecord r = new EscherContainerRecord();
r.AddChildRecord(new DummyEscherRecord());
Assert.AreEqual(18, r.RecordSize);
}
/**
* We were having problems with Reading too much data on an UnknownEscherRecord,
* but hopefully we now Read the correct size.
*/
[Test]
public void TestBug44857()
{
byte[] data = _samples.ReadFile("Container.dat");
// This used to fail with an OutOfMemory
EscherContainerRecord record = new EscherContainerRecord();
record.FillFields(data, 0, new DefaultEscherRecordFactory());
}
/**
* Ensure {@link EscherContainerRecord} doesn't spill its guts everywhere
*/
[Test]
public void TestChildren()
{
EscherContainerRecord ecr = new EscherContainerRecord();
List<EscherRecord> children0 = ecr.ChildRecords;
Assert.AreEqual(0, children0.Count);
EscherRecord chA = new DummyEscherRecord();
EscherRecord chB = new DummyEscherRecord();
EscherRecord chC = new DummyEscherRecord();
ecr.AddChildRecord(chA);
ecr.AddChildRecord(chB);
children0.Add(chC);
List<EscherRecord> children1 = ecr.ChildRecords;
Assert.IsTrue(children0 != children1);
Assert.AreEqual(2, children1.Count);
Assert.AreEqual(chA, children1[0]);
Assert.AreEqual(chB, children1[1]);
Assert.AreEqual(1, children0.Count); // first copy unchanged
ecr.ChildRecords=(children0);
ecr.AddChildRecord(chA);
List<EscherRecord> children2 = ecr.ChildRecords;
Assert.AreEqual(2, children2.Count);
Assert.AreEqual(chC, children2[0]);
Assert.AreEqual(chA, children2[1]);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using BitbucketCoreReceiver;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.WebHooks.FunctionalTest
{
public class BitbucketCoreReceiverTest : IClassFixture<WebHookTestFixture<Startup>>
{
private readonly HttpClient _client;
private readonly WebHookTestFixture<Startup> _fixture;
public BitbucketCoreReceiverTest(WebHookTestFixture<Startup> fixture)
{
_client = fixture.CreateClient();
_fixture = fixture;
}
[Fact]
public async Task HomePage_IsNotFound()
{
// Arrange & Act
var response = await _client.GetAsync("/");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task WebHookAction_NoEventHeader_IsNotFound()
{
// Arrange
var content = new StringContent(string.Empty);
var request = new HttpRequestMessage(
HttpMethod.Post,
"/api/webhooks/incoming/bitbucket?code=01234567890123456789012345678901")
{
Content = content,
};
// Act
var response = await _client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
var responseText = await response.Content.ReadAsStringAsync();
// This requirement is enforced in a constraint. Therefore, response is empty.
Assert.Empty(responseText);
}
public static TheoryData<HttpMethod> NonPostDataSet
{
get
{
return new TheoryData<HttpMethod>
{
HttpMethod.Get,
HttpMethod.Head,
HttpMethod.Put,
};
}
}
[Theory]
[MemberData(nameof(NonPostDataSet))]
public async Task WebHookAction_NonPost_IsNotAllowed(HttpMethod method)
{
// Arrange
var expectedErrorMessage = "The 'bitbucket' WebHook receiver does not support the HTTP " +
$"'{method.Method}' method.";
var request = new HttpRequestMessage(
method,
"/api/webhooks/incoming/bitbucket?code=01234567890123456789012345678901")
{
Headers =
{
{ BitbucketConstants.EventHeaderName, "bitbucket:push" },
{ BitbucketConstants.WebHookIdHeaderName, "01234" },
},
};
// Act
var response = await _client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.MethodNotAllowed, response.StatusCode);
var responseText = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedErrorMessage, responseText);
}
[Fact]
public async Task WebHookAction_NoCode_IsBadRequest()
{
// Arrange
var expectedErrorMessage = "A 'bitbucket' WebHook request must contain a 'code' query parameter.";
var content = new StringContent(string.Empty);
var request = new HttpRequestMessage(HttpMethod.Post, "/api/webhooks/incoming/bitbucket")
{
Content = content,
Headers =
{
{ BitbucketConstants.EventHeaderName, "bitbucket:push" },
},
};
// Act
var response = await _client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var responseText = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedErrorMessage, responseText);
}
[Fact]
public async Task WebHookAction_WrongCode_IsBadRequest()
{
// Arrange
var expectedErrorMessage = "The 'code' query parameter provided in the HTTP request did not match the " +
"expected value.";
var content = new StringContent(string.Empty);
var request = new HttpRequestMessage(
HttpMethod.Post,
// One changed character in code query parameter.
"/api/webhooks/incoming/bitbucket?code=01234567890123456789012345678902")
{
Content = content,
Headers =
{
{ BitbucketConstants.EventHeaderName, "bitbucket:push" },
},
};
// Act
var response = await _client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var responseText = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedErrorMessage, responseText);
}
[Fact]
public async Task WebHookAction_NoUUID_IsBadRequest()
{
// Arrange
var expectedErrorMessage = "A 'bitbucket' WebHook request must contain a " +
$"'{BitbucketConstants.WebHookIdHeaderName}' HTTP header.";
var content = new StringContent(string.Empty);
var request = new HttpRequestMessage(
HttpMethod.Post,
// One changed character in code query parameter.
"/api/webhooks/incoming/bitbucket?code=01234567890123456789012345678901")
{
Content = content,
Headers =
{
{ BitbucketConstants.EventHeaderName, "bitbucket:push" },
},
};
// Act
var response = await _client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var responseText = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedErrorMessage, responseText);
}
[Fact]
public async Task WebHookAction_NoBody_IsBadRequest()
{
// Arrange
var expectedErrorMessage = "The 'bitbucket' WebHook receiver does not support an empty request body.";
var content = new StringContent(string.Empty);
var request = new HttpRequestMessage(
HttpMethod.Post,
"/api/webhooks/incoming/bitbucket?code=01234567890123456789012345678901")
{
Content = content,
Headers =
{
{ BitbucketConstants.EventHeaderName, "bitbucket:push" },
{ BitbucketConstants.WebHookIdHeaderName, "01234" },
},
};
// Act
var response = await _client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var responseText = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedErrorMessage, responseText);
}
[Fact]
public async Task WebHookAction_WithBody_Succeeds()
{
// Arrange
var fixture = _fixture.WithTestLogger(out var testSink);
var client = fixture.CreateClient();
var path = Path.Combine("Resources", "RequestBodies", "Bitbucket.json");
var stream = await ResourceFile.GetResourceStreamAsync(path, normalizeLineEndings: true);
var content = new StreamContent(stream)
{
Headers =
{
{ HeaderNames.ContentLength, stream.Length.ToString() },
{ HeaderNames.ContentType, "text/json" },
},
};
var request = new HttpRequestMessage(
HttpMethod.Post,
"/api/webhooks/incoming/bitbucket?code=01234567890123456789012345678901")
{
Content = content,
Headers =
{
{ BitbucketConstants.EventHeaderName, "repo:push" },
{ BitbucketConstants.WebHookIdHeaderName, "01234" },
},
};
// Act
var response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var responseText = await response.Content.ReadAsStringAsync();
Assert.Empty(responseText);
}
}
}
| |
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 CanadaAlertSystemApi.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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;
}
}
}
| |
//
// MassStorageSource.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.Collections;
using Banshee.IO;
using Banshee.Dap;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.Library;
using Banshee.Query;
using Banshee.Sources;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Hardware;
using Banshee.Playlists.Formats;
using Banshee.Playlist;
namespace Banshee.Dap.MassStorage
{
public class MassStorageSource : DapSource
{
private Banshee.Collection.Gui.ArtworkManager artwork_manager
= ServiceManager.Get<Banshee.Collection.Gui.ArtworkManager> ();
private MassStorageDevice ms_device;
private IVolume volume;
private IUsbDevice usb_device;
public override void DeviceInitialize (IDevice device, bool force)
{
base.DeviceInitialize (device, force);
volume = device as IVolume;
if (volume == null || (usb_device = volume.ResolveRootUsbDevice ()) == null) {
throw new InvalidDeviceException ();
}
if (!volume.IsMounted && !volume.CanMount) {
throw new InvalidDeviceException ();
} else if (!volume.IsMounted) {
volume.Mount ();
}
ms_device = DeviceMapper.Map (this);
try {
if (ms_device.ShouldIgnoreDevice () || !ms_device.LoadDeviceConfiguration ()) {
ms_device = null;
}
} catch (Exception e) {
Log.Error (e);
ms_device = null;
}
if (!HasMediaCapabilities && ms_device == null) {
throw new InvalidDeviceException ();
}
// Ignore iPods, except ones with .is_audio_player files
if (MediaCapabilities != null && MediaCapabilities.IsType ("ipod")) {
if (ms_device != null && ms_device.HasIsAudioPlayerFile) {
Log.Information (
"Mass Storage Support Loading iPod",
"The USB mass storage audio player support is loading an iPod because it has an .is_audio_player file. " +
"If you aren't running Rockbox or don't know what you're doing, things might not behave as expected."
);
} else {
throw new InvalidDeviceException ();
}
}
Name = ms_device == null ? volume.Name : ms_device.Name;
mount_point = volume.MountPoint;
Initialize ();
if (ms_device != null) {
ms_device.SourceInitialize ();
}
AddDapProperties ();
// TODO differentiate between Audio Players and normal Disks, and include the size, eg "2GB Audio Player"?
//GenericName = Catalog.GetString ("Audio Player");
}
private void AddDapProperties ()
{
if (AudioFolders.Length > 0 && !String.IsNullOrEmpty (AudioFolders[0])) {
AddDapProperty (String.Format (
Catalog.GetPluralString ("Audio Folder", "Audio Folders", AudioFolders.Length), AudioFolders.Length),
System.String.Join ("\n", AudioFolders)
);
}
if (VideoFolders.Length > 0 && !String.IsNullOrEmpty (VideoFolders[0])) {
AddDapProperty (String.Format (
Catalog.GetPluralString ("Video Folder", "Video Folders", VideoFolders.Length), VideoFolders.Length),
System.String.Join ("\n", VideoFolders)
);
}
if (FolderDepth != -1) {
AddDapProperty (Catalog.GetString ("Required Folder Depth"), FolderDepth.ToString ());
}
AddYesNoDapProperty (Catalog.GetString ("Supports Playlists"), PlaylistTypes.Count > 0);
/*if (AcceptableMimeTypes.Length > 0) {
AddDapProperty (String.Format (
Catalog.GetPluralString ("Audio Format", "Audio Formats", PlaybackFormats.Length), PlaybackFormats.Length),
System.String.Join (", ", PlaybackFormats)
);
}*/
}
private System.Threading.ManualResetEvent import_reset_event;
private DatabaseImportManager importer;
// WARNING: This will be called from a thread!
protected override void LoadFromDevice ()
{
import_reset_event = new System.Threading.ManualResetEvent (false);
importer = new DatabaseImportManager (this) {
KeepUserJobHidden = true,
SkipHiddenChildren = false
};
importer.Finished += OnImportFinished;
foreach (string audio_folder in BaseDirectories) {
importer.Enqueue (audio_folder);
}
import_reset_event.WaitOne ();
}
private void OnImportFinished (object o, EventArgs args)
{
importer.Finished -= OnImportFinished;
if (CanSyncPlaylists) {
var insert_cmd = new Hyena.Data.Sqlite.HyenaSqliteCommand (
"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) VALUES (?, ?)");
foreach (string playlist_path in PlaylistFiles) {
// playlist_path has a file:// prefix, and GetDirectoryName messes it up,
// so we need to convert it to a regular path
string base_folder = ms_device.RootPath != null ? BaseDirectory :
System.IO.Path.GetDirectoryName (SafeUri.UriToFilename (playlist_path));
IPlaylistFormat loaded_playlist = PlaylistFileUtil.Load (playlist_path,
new Uri (base_folder),
ms_device.RootPath);
if (loaded_playlist == null)
continue;
string name = System.IO.Path.GetFileNameWithoutExtension (SafeUri.UriToFilename (playlist_path));
PlaylistSource playlist = new PlaylistSource (name, this);
playlist.Save ();
//Hyena.Data.Sqlite.HyenaSqliteCommand.LogAll = true;
foreach (PlaylistElement element in loaded_playlist.Elements) {
string track_path = element.Uri.LocalPath;
long track_id = DatabaseTrackInfo.GetTrackIdForUri (new SafeUri (track_path), DbId);
if (track_id == 0) {
Log.DebugFormat ("Failed to find track {0} in DAP library to load it into playlist {1}", track_path, playlist_path);
} else {
ServiceManager.DbConnection.Execute (insert_cmd, playlist.DbId, track_id);
}
}
//Hyena.Data.Sqlite.HyenaSqliteCommand.LogAll = false;
playlist.UpdateCounts ();
AddChildSource (playlist);
}
}
import_reset_event.Set ();
}
public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
{
if (track.PrimarySourceId == DbId) {
Banshee.IO.File.Copy (track.Uri, uri, false);
}
}
public override void Import ()
{
var importer = new LibraryImportManager (true) {
SkipHiddenChildren = false
};
foreach (string audio_folder in BaseDirectories) {
importer.Enqueue (audio_folder);
}
}
public IVolume Volume {
get { return volume; }
}
public IUsbDevice UsbDevice {
get { return usb_device; }
}
private string mount_point;
public override string BaseDirectory {
get { return mount_point; }
}
protected override IDeviceMediaCapabilities MediaCapabilities {
get {
return ms_device ?? (
volume.Parent == null
? base.MediaCapabilities
: volume.Parent.MediaCapabilities ?? base.MediaCapabilities
);
}
}
#region Properties and Methods for Supporting Syncing of Playlists
private string [] playlists_paths;
private string [] PlaylistsPaths {
get {
if (playlists_paths == null) {
if (MediaCapabilities == null || MediaCapabilities.PlaylistPaths == null
|| MediaCapabilities.PlaylistPaths.Length == 0) {
playlists_paths = new string [] { WritePath };
} else {
playlists_paths = new string [MediaCapabilities.PlaylistPaths.Length];
for (int i = 0; i < MediaCapabilities.PlaylistPaths.Length; i++) {
playlists_paths[i] = Paths.Combine (BaseDirectory, MediaCapabilities.PlaylistPaths[i]);
playlists_paths[i] = playlists_paths[i].Replace ("%File", String.Empty);
}
}
}
return playlists_paths;
}
}
private string playlists_write_path;
private string PlaylistsWritePath {
get {
if (playlists_write_path == null) {
playlists_write_path = WritePath;
// We write playlists to the first folder listed in the PlaylistsPath property
if (PlaylistsPaths.Length > 0) {
playlists_write_path = PlaylistsPaths[0];
}
if (!Directory.Exists (playlists_write_path)) {
Directory.Create (playlists_write_path);
}
}
return playlists_write_path;
}
}
private string [] playlist_formats;
private string [] PlaylistFormats {
get {
if (playlist_formats == null && MediaCapabilities != null) {
playlist_formats = MediaCapabilities.PlaylistFormats;
}
return playlist_formats;
}
set { playlist_formats = value; }
}
private List<PlaylistFormatDescription> playlist_types;
private IList<PlaylistFormatDescription> PlaylistTypes {
get {
if (playlist_types == null) {
playlist_types = new List<PlaylistFormatDescription> ();
if (PlaylistFormats != null) {
foreach (PlaylistFormatDescription desc in Banshee.Playlist.PlaylistFileUtil.ExportFormats) {
foreach (string mimetype in desc.MimeTypes) {
if (Array.IndexOf (PlaylistFormats, mimetype) != -1) {
playlist_types.Add (desc);
break;
}
}
}
}
}
SupportsPlaylists &= CanSyncPlaylists;
return playlist_types;
}
}
private IEnumerable<string> PlaylistFiles {
get {
foreach (string folder_name in PlaylistsPaths) {
if (!Directory.Exists (folder_name)) {
continue;
}
foreach (string file_name in Directory.GetFiles (folder_name)) {
foreach (PlaylistFormatDescription desc in playlist_types) {
if (file_name.EndsWith (desc.FileExtension)) {
yield return file_name;
break;
}
}
}
}
}
}
private bool CanSyncPlaylists {
get {
return PlaylistsWritePath != null && playlist_types.Count > 0;
}
}
public override void SyncPlaylists ()
{
if (!CanSyncPlaylists) {
return;
}
foreach (string file_name in PlaylistFiles) {
try {
Banshee.IO.File.Delete (new SafeUri (file_name));
} catch (Exception e) {
Log.Error (e);
}
}
// Add playlists from Banshee to the device
PlaylistFormatBase playlist_format = null;
List<Source> children = new List<Source> (Children);
foreach (Source child in children) {
PlaylistSource from = child as PlaylistSource;
string escaped_name = StringUtil.EscapeFilename (child.Name);
if (from != null && !String.IsNullOrEmpty (escaped_name)) {
from.Reload ();
if (playlist_format == null) {
playlist_format = Activator.CreateInstance (PlaylistTypes[0].Type) as PlaylistFormatBase;
playlist_format.FolderSeparator = MediaCapabilities.FolderSeparator;
}
SafeUri playlist_path = new SafeUri (System.IO.Path.Combine (
PlaylistsWritePath, String.Format ("{0}.{1}", escaped_name, PlaylistTypes[0].FileExtension)));
System.IO.Stream stream = null;
try {
stream = Banshee.IO.File.OpenWrite (playlist_path, true);
if (ms_device.RootPath == null) {
playlist_format.BaseUri = new Uri (PlaylistsWritePath);
} else {
playlist_format.RootPath = ms_device.RootPath;
playlist_format.BaseUri = new Uri (BaseDirectory);
}
playlist_format.Save (stream, from);
} catch (Exception e) {
Log.Error (e);
} finally {
stream.Close ();
}
}
}
}
#endregion
protected override string [] GetIconNames ()
{
string [] names = ms_device != null ? ms_device.GetIconNames () : null;
return names == null ? base.GetIconNames () : names;
}
public override long BytesUsed {
get { return BytesCapacity - volume.Available; }
}
public override long BytesCapacity {
get { return (long) volume.Capacity; }
}
private bool had_write_error = false;
public override bool IsReadOnly {
get { return volume.IsReadOnly || had_write_error; }
}
private string write_path = null;
public string WritePath {
get {
if (write_path == null) {
write_path = BaseDirectory;
// According to the HAL spec, the first folder listed in the audio_folders property
// is the folder to write files to.
if (AudioFolders.Length > 0) {
write_path = Hyena.Paths.Combine (write_path, AudioFolders[0]);
}
}
return write_path;
}
set { write_path = value; }
}
private string write_path_video = null;
public string WritePathVideo {
get {
if (write_path_video == null) {
write_path_video = BaseDirectory;
// Some Devices May Have a Separate Video Directory
if (VideoFolders.Length > 0) {
write_path_video = Hyena.Paths.Combine (write_path_video, VideoFolders[0]);
} else if (AudioFolders.Length > 0) {
write_path_video = Hyena.Paths.Combine (write_path_video, AudioFolders[0]);
write_path_video = Hyena.Paths.Combine (write_path_video, "Videos");
}
}
return write_path_video;
}
set { write_path_video = value; }
}
private string [] audio_folders;
protected string [] AudioFolders {
get {
if (audio_folders == null) {
audio_folders = HasMediaCapabilities ? MediaCapabilities.AudioFolders : new string[0];
}
return audio_folders;
}
set { audio_folders = value; }
}
private string [] video_folders;
protected string [] VideoFolders {
get {
if (video_folders == null) {
video_folders = HasMediaCapabilities ? MediaCapabilities.VideoFolders : new string[0];
}
return video_folders;
}
set { video_folders = value; }
}
protected IEnumerable<string> BaseDirectories {
get {
if (AudioFolders.Length == 0) {
yield return BaseDirectory;
} else {
foreach (string audio_folder in AudioFolders) {
yield return Paths.Combine (BaseDirectory, audio_folder);
}
}
}
}
private int folder_depth = -1;
protected int FolderDepth {
get {
if (folder_depth == -1) {
folder_depth = HasMediaCapabilities ? MediaCapabilities.FolderDepth : -1;
}
return folder_depth;
}
set { folder_depth = value; }
}
private int cover_art_size = -1;
protected int CoverArtSize {
get {
if (cover_art_size == -1) {
cover_art_size = HasMediaCapabilities ? MediaCapabilities.CoverArtSize : 0;
}
return cover_art_size;
}
set { cover_art_size = value; }
}
private string cover_art_file_name = null;
protected string CoverArtFileName {
get {
if (cover_art_file_name == null) {
cover_art_file_name = HasMediaCapabilities ? MediaCapabilities.CoverArtFileName : null;
}
return cover_art_file_name;
}
set { cover_art_file_name = value; }
}
private string cover_art_file_type = null;
protected string CoverArtFileType {
get {
if (cover_art_file_type == null) {
cover_art_file_type = HasMediaCapabilities ? MediaCapabilities.CoverArtFileType : null;
}
return cover_art_file_type;
}
set { cover_art_file_type = value; }
}
public override void UpdateMetadata (DatabaseTrackInfo track)
{
SafeUri new_uri = new SafeUri (GetTrackPath (track, System.IO.Path.GetExtension (track.Uri)));
if (new_uri.ToString () != track.Uri.ToString ()) {
Directory.Create (System.IO.Path.GetDirectoryName (new_uri.LocalPath));
Banshee.IO.File.Move (track.Uri, new_uri);
//to remove the folder if it's not needed anymore:
DeleteTrackFile (track);
track.Uri = new_uri;
track.Save (true, BansheeQuery.UriField);
}
base.UpdateMetadata (track);
}
protected override void AddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri)
{
if (track.PrimarySourceId == DbId)
return;
SafeUri new_uri = new SafeUri (GetTrackPath (track, System.IO.Path.GetExtension (fromUri)));
// If it already is on the device but it's out of date, remove it
//if (File.Exists(new_uri) && File.GetLastWriteTime(track.Uri.LocalPath) > File.GetLastWriteTime(new_uri))
//RemoveTrack(new MassStorageTrackInfo(new SafeUri(new_uri)));
if (!File.Exists (new_uri)) {
Directory.Create (System.IO.Path.GetDirectoryName (new_uri.LocalPath));
File.Copy (fromUri, new_uri, false);
DatabaseTrackInfo copied_track = new DatabaseTrackInfo (track);
copied_track.PrimarySource = this;
copied_track.Uri = new_uri;
// Write the metadata in db to the file on the DAP if it has changed since file was modified
// to ensure that when we load it next time, it's data will match what's in the database
// and the MetadataHash will actually match. We do this by comparing the time
// stamps on files for last update of the db metadata vs the sync to file.
// The equals on the inequality below is necessary for podcasts who often have a sync and
// update time that are the same to the second, even though the album metadata has changed in the
// DB to the feedname instead of what is in the file. It should be noted that writing the metadata
// is a small fraction of the total copy time anyway.
if (track.LastSyncedStamp >= Hyena.DateTimeUtil.ToDateTime (track.FileModifiedStamp)) {
Log.DebugFormat ("Copying Metadata to File Since Sync time >= Updated Time");
bool write_metadata = Metadata.SaveTrackMetadataService.WriteMetadataEnabled.Value;
bool write_ratings = Metadata.SaveTrackMetadataService.WriteRatingsEnabled.Value;
bool write_playcounts = Metadata.SaveTrackMetadataService.WritePlayCountsEnabled.Value;
Banshee.Streaming.StreamTagger.SaveToFile (copied_track, write_metadata, write_ratings, write_playcounts);
}
copied_track.Save (false);
}
if (CoverArtSize > -1 && !String.IsNullOrEmpty (CoverArtFileType) &&
!String.IsNullOrEmpty (CoverArtFileName) && (FolderDepth == -1 || FolderDepth > 0)) {
SafeUri cover_uri = new SafeUri (System.IO.Path.Combine (System.IO.Path.GetDirectoryName (new_uri.LocalPath),
CoverArtFileName));
string coverart_id = track.ArtworkId;
if (!File.Exists (cover_uri) && CoverArtSpec.CoverExists (coverart_id)) {
Gdk.Pixbuf pic = null;
if (CoverArtSize == 0) {
if (CoverArtFileType == "jpg" || CoverArtFileType == "jpeg") {
SafeUri local_cover_uri = new SafeUri (Banshee.Base.CoverArtSpec.GetPath (coverart_id));
Banshee.IO.File.Copy (local_cover_uri, cover_uri, false);
} else {
pic = artwork_manager.LookupPixbuf (coverart_id);
}
} else {
pic = artwork_manager.LookupScalePixbuf (coverart_id, CoverArtSize);
}
if (pic != null) {
try {
byte [] bytes = pic.SaveToBuffer (CoverArtFileType);
System.IO.Stream cover_art_file = File.OpenWrite (cover_uri, true);
cover_art_file.Write (bytes, 0, bytes.Length);
cover_art_file.Close ();
} catch (GLib.GException){
Log.DebugFormat ("Could not convert cover art to {0}, unsupported filetype?", CoverArtFileType);
} finally {
Banshee.Collection.Gui.ArtworkManager.DisposePixbuf (pic);
}
}
}
}
}
protected override bool DeleteTrack (DatabaseTrackInfo track)
{
if (ms_device != null && !ms_device.DeleteTrackHook (track)) {
return false;
}
DeleteTrackFile (track);
return true;
}
private void DeleteTrackFile (DatabaseTrackInfo track)
{
try {
string track_file = System.IO.Path.GetFileName (track.Uri.LocalPath);
string track_dir = System.IO.Path.GetDirectoryName (track.Uri.LocalPath);
int files = 0;
// Count how many files remain in the track's directory,
// excluding self or cover art
foreach (string file in System.IO.Directory.GetFiles (track_dir)) {
string relative = System.IO.Path.GetFileName (file);
if (relative != track_file && relative != CoverArtFileName) {
files++;
}
}
// If we are the last track, go ahead and delete the artwork
// to ensure that the directory tree can get trimmed away too
if (files == 0 && CoverArtFileName != null) {
System.IO.File.Delete (Paths.Combine (track_dir, CoverArtFileName));
}
if (Banshee.IO.File.Exists (track.Uri)) {
Banshee.IO.Utilities.DeleteFileTrimmingParentDirectories (track.Uri);
} else {
Banshee.IO.Utilities.TrimEmptyDirectories (track.Uri);
}
} catch (System.IO.FileNotFoundException) {
} catch (System.IO.DirectoryNotFoundException) {
}
}
protected override void Eject ()
{
base.Eject ();
if (volume.CanUnmount) {
volume.Unmount ();
}
if (volume.CanEject) {
volume.Eject ();
}
}
protected override bool CanHandleDeviceCommand (DeviceCommand command)
{
try {
SafeUri uri = new SafeUri (command.DeviceId);
return BaseDirectory.StartsWith (uri.LocalPath);
} catch (Exception e) {
Log.Error (e);
return false;
}
}
private string GetTrackPath (TrackInfo track, string ext)
{
string file_path = null;
if (track.HasAttribute (TrackMediaAttributes.Podcast)) {
string album = FileNamePattern.Escape (track.DisplayAlbumTitle);
string title = FileNamePattern.Escape (track.DisplayTrackTitle);
file_path = System.IO.Path.Combine ("Podcasts", album);
file_path = System.IO.Path.Combine (file_path, title);
} else if (track.HasAttribute (TrackMediaAttributes.VideoStream)) {
string album = FileNamePattern.Escape (track.DisplayAlbumTitle);
string title = FileNamePattern.Escape (track.DisplayTrackTitle);
file_path = System.IO.Path.Combine (album, title);
} else if (ms_device == null || !ms_device.GetTrackPath (track, out file_path)) {
// If the folder_depth property exists, we have to put the files in a hiearchy of
// the exact given depth (not including the mount point/audio_folder).
if (FolderDepth != -1) {
int depth = FolderDepth;
bool is_album_unknown = String.IsNullOrEmpty (track.AlbumTitle);
string album_artist = FileNamePattern.Escape (track.DisplayAlbumArtistName);
string track_album = FileNamePattern.Escape (track.DisplayAlbumTitle);
string track_number = FileNamePattern.Escape (String.Format ("{0:00}", track.TrackNumber));
string track_title = FileNamePattern.Escape (track.DisplayTrackTitle);
if (depth == 0) {
// Artist - Album - 01 - Title
string track_artist = FileNamePattern.Escape (track.DisplayArtistName);
file_path = is_album_unknown ?
String.Format ("{0} - {1} - {2}", track_artist, track_number, track_title) :
String.Format ("{0} - {1} - {2} - {3}", track_artist, track_album, track_number, track_title);
} else if (depth == 1) {
// Artist - Album/01 - Title
file_path = is_album_unknown ?
album_artist :
String.Format ("{0} - {1}", album_artist, track_album);
file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title));
} else if (depth == 2) {
// Artist/Album/01 - Title
file_path = album_artist;
if (!is_album_unknown || ms_device.MinimumFolderDepth == depth) {
file_path = System.IO.Path.Combine (file_path, track_album);
}
file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title));
} else {
// If the *required* depth is more than 2..go nuts!
for (int i = 0; i < depth - 2; i++) {
if (i == 0) {
file_path = album_artist.Substring (0, Math.Min (i+1, album_artist.Length)).Trim ();
} else {
file_path = System.IO.Path.Combine (file_path, album_artist.Substring (0, Math.Min (i+1, album_artist.Length)).Trim ());
}
}
// Finally add on the Artist/Album/01 - Track
file_path = System.IO.Path.Combine (file_path, album_artist);
file_path = System.IO.Path.Combine (file_path, track_album);
file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title));
}
} else {
file_path = MusicLibrarySource.MusicFileNamePattern.CreateFromTrackInfo (track);
}
}
if (track.HasAttribute (TrackMediaAttributes.VideoStream)) {
file_path = System.IO.Path.Combine (WritePathVideo, file_path);
} else {
file_path = System.IO.Path.Combine (WritePath, file_path);
}
file_path += ext;
return file_path;
}
public override bool HasEditableTrackProperties {
get { return true; }
}
}
}
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
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.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Tilde.Framework.View;
using System.IO;
using WeifenLuo.WinFormsUI.Docking;
using Tilde.Framework.Controls;
namespace Tilde.TildeApp
{
public partial class DocumentSwitchWindow : Form
{
MainWindow mMainWindow;
DockContent mSelectedContent;
public struct ButtonSettings
{
public Brush mLabelBrush;
public StringFormat mLabelFormat;
}
public class FileButton : Button
{
ButtonSettings mButtonSettings;
public FileButton(ButtonSettings settings)
{
mButtonSettings = settings;
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
// base.OnPaintBackground(pevent);
}
protected override void OnPaint(PaintEventArgs pevent)
{
RectangleF rect = new RectangleF(this.DisplayRectangle.Left + this.Padding.Left, this.DisplayRectangle.Top + this.Padding.Top, this.DisplayRectangle.Width - this.Padding.Horizontal - 1, this.DisplayRectangle.Height - this.Padding.Vertical - 1);
if (this.Focused)
{
pevent.Graphics.Clear(Color.LightSteelBlue);
pevent.Graphics.DrawRectangle(SystemPens.WindowFrame, Rectangle.Round(rect));
}
else
{
pevent.Graphics.Clear(SystemColors.Control);
}
pevent.Graphics.DrawString(this.Text, this.Font, mButtonSettings.mLabelBrush, rect, mButtonSettings.mLabelFormat);
}
}
ButtonSettings mButtonSettings;
public DocumentSwitchWindow(MainWindow window)
{
InitializeComponent();
mMainWindow = window;
mSelectedContent = null;
//SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
mButtonSettings = new ButtonSettings();
mButtonSettings.mLabelBrush = new SolidBrush(Button.DefaultForeColor);
mButtonSettings.mLabelFormat = new StringFormat(StringFormatFlags.NoWrap);
mButtonSettings.mLabelFormat.Trimming = StringTrimming.EllipsisCharacter;
mButtonSettings.mLabelFormat.Alignment = StringAlignment.Near;
mButtonSettings.mLabelFormat.LineAlignment = StringAlignment.Center;
}
public DockContent SelectedContent
{
get { return mSelectedContent; }
}
private void DocumentSwitchWindow_KeyDown(object sender, KeyEventArgs e)
{
System.Diagnostics.Debug.Print("KeyCode=[" + e.KeyData.ToString() + "] KeyData=[" + e.KeyData.ToString() + "] KeyCode=[" + e.KeyCode.ToString() + "]");
if (e.KeyCode == Keys.Tab)
{
/*
Control next = this.GetNextControl(Control.FromHandle(Win32.GetFocus()), !e.Shift);
if (next == null && panelActiveFiles.Controls.Count > 0)
next = panelActiveFiles.Controls[e.Shift ? panelActiveFiles.Controls.Count - 1 : 0];
if(next != null)
next.Select();
*/
Control focusControl;
if (this.ActiveControl.Parent == panelActiveFiles)
focusControl = panelActiveFiles;
else if (this.ActiveControl.Parent == panelActiveToolWindows)
focusControl = panelActiveToolWindows;
else
focusControl = this;
focusControl.SelectNextControl(this.ActiveControl, !e.Shift, true, true, true);
e.Handled = true;
}
}
private void DocumentSwitchWindow_KeyUp(object sender, KeyEventArgs e)
{
if (!e.Control)
{
Control focused = Control.FromHandle(Win32.GetFocus());
this.DialogResult = DialogResult.OK;
if (focused is Button)
{
DockContent content = (focused as Button).Tag as DockContent;
ActivateDockContent(content);
}
e.Handled = true;
}
}
public void UpdateWindows()
{
int docIndex = 0;
int toolIndex = 0;
List<Button> fileButtons = new List<Button>();
List<Button> toolButtons = new List<Button>();
foreach (IDockContent icontent in mMainWindow.DockContentHistory)
{
DockContent content = icontent as DockContent;
if (content != null)
{
Button button = new FileButton(mButtonSettings);
button.Tag = content;
button.Text = content.TabText;
button.TextAlign = ContentAlignment.MiddleLeft;
button.FlatStyle = FlatStyle.Flat;
button.AutoEllipsis = true;
button.Margin = new Padding(1);
button.Width = 160;
button.Height -= 6;
button.Enter += new EventHandler(FileButton_Enter);
button.Leave += new EventHandler(FileButton_Leave);
button.MouseClick += new MouseEventHandler(FileButton_MouseClick);
if (content.DockState == DockState.Document)
{
button.TabIndex = docIndex++;
fileButtons.Add(button);
}
else
{
button.TabIndex = toolIndex++;
toolButtons.Add(button);
}
}
}
this.SuspendLayout();
panelActiveFiles.SuspendLayout();
panelActiveFiles.Controls.Clear();
panelActiveFiles.Controls.AddRange(fileButtons.ToArray());
panelActiveFiles.ResumeLayout();
panelActiveToolWindows.SuspendLayout();
panelActiveToolWindows.Controls.Clear();
panelActiveToolWindows.Controls.AddRange(toolButtons.ToArray());
panelActiveToolWindows.ResumeLayout();
this.ResumeLayout();
if (panelActiveFiles.Controls.Count > 1)
panelActiveFiles.Controls[1].Select();
else if (panelActiveFiles.Controls.Count > 0)
panelActiveFiles.Controls[0].Select();
}
void FileButton_Enter(object sender, EventArgs e)
{
DockContent content = (sender as Button).Tag as DockContent;
DocumentView view = (sender as Button).Tag as DocumentView;
labelDocumentName.Text = view != null ? Path.GetFileName(view.Document.FileName) : content.TabText;
labelDocumentPath.Text = view != null ? view.Document.FileName : "";
labelDocumentType.Text = view != null ? view.GetType().ToString() : "";
}
void FileButton_Leave(object sender, EventArgs e)
{
labelDocumentName.Text = "";
labelDocumentPath.Text = "";
labelDocumentType.Text = "";
}
void FileButton_MouseClick(object sender, MouseEventArgs e)
{
DockContent content = (sender as Button).Tag as DockContent;
ActivateDockContent(content);
}
void ActivateDockContent(DockContent content)
{
mSelectedContent = content;
this.DialogResult = DialogResult.OK;
}
}
}
| |
#region Using directives
#define USE_TRACING
using System;
using System.Collections;
using System.Collections.Generic;
#endregion
//////////////////////////////////////////////////////////////////////
// contains typed collections based on the 1.1 .NET framework
// using typed collections has the benefit of additional code reliability
// and using them in the collection editor
//
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Client
{
//////////////////////////////////////////////////////////////////////
/// <summary>standard typed collection based on 1.1 framework for FeedEntries
/// </summary>
//////////////////////////////////////////////////////////////////////
public class AtomEntryCollection : AtomCollectionBase<AtomEntry>
{
/// <summary>holds the owning feed</summary>
private readonly AtomFeed feed;
/// <summary>private default constructor</summary>
private AtomEntryCollection()
{
}
/// <summary>constructor</summary>
public AtomEntryCollection(AtomFeed feed)
{
this.feed = feed;
}
/// <summary>standard typed accessor method </summary>
public override AtomEntry this[int index]
{
get { return List[index]; }
set
{
if (value != null)
{
if (value.Feed == null || value.Feed != feed)
{
value.setFeed(feed);
}
}
List[index] = value;
}
}
/// <summary>Fins an atomEntry in the collection
/// based on it's ID. </summary>
/// <param name="value">The atomId to look for</param>
/// <returns>Null if not found, otherwise the entry</returns>
public AtomEntry FindById(AtomId value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
foreach (AtomEntry entry in List)
{
if (entry.Id.AbsoluteUri == value.AbsoluteUri)
{
return entry;
}
}
return null;
}
/// <summary>standard typed add method </summary>
public override void Add(AtomEntry value)
{
if (value != null)
{
if (feed != null && value.Feed == feed)
{
// same object, already in here.
throw new ArgumentException("The entry is already part of this collection");
}
value.setFeed(feed);
// old code
/*
// now we need to see if this is the same feed. If not, copy
if (AtomFeed.IsFeedIdentical(value.Feed, this.feed) == false)
{
AtomEntry newEntry = AtomEntry.ImportFromFeed(value);
newEntry.setFeed(this.feed);
value = newEntry;
}
*/
// from now on, we will only ADD the entry to this collection and change it's
// ownership. No more auto-souce creation. There is an explicit method for this
value.ProtocolMajor = feed.ProtocolMajor;
value.ProtocolMinor = feed.ProtocolMinor;
}
base.Add(value);
}
/// <summary>
/// takes an existing atomentry object and either copies it into this feed collection,
/// or moves it by creating a source element and copying it in here if the value is actually
/// already part of a collection
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public AtomEntry CopyOrMove(AtomEntry value)
{
if (value != null)
{
if (value.Feed == null)
{
value.setFeed(feed);
}
else
{
if (feed != null && value.Feed == feed)
{
// same object, already in here.
throw new ArgumentException("The entry is already part of this collection");
}
// now we need to see if this is the same feed. If not, copy
if (!AtomFeed.IsFeedIdentical(value.Feed, feed))
{
AtomEntry newEntry = AtomEntry.ImportFromFeed(value);
newEntry.setFeed(feed);
value = newEntry;
}
}
value.ProtocolMajor = feed.ProtocolMajor;
value.ProtocolMinor = feed.ProtocolMinor;
}
base.Add(value);
return value;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>standard typed collection based on 1.1 framework for AtomLinks
/// </summary>
//////////////////////////////////////////////////////////////////////
public class AtomLinkCollection : AtomCollectionBase<AtomLink>
{
//////////////////////////////////////////////////////////////////////
/// <summary>public AtomLink FindService(string service,string type)
/// Retrieves the first link with the supplied 'rel' and/or 'type' value.
/// If either parameter is null, the corresponding match isn't needed.
/// </summary>
/// <param name="service">the service entry to find</param>
/// <param name="type">the link type to find</param>
/// <returns>the found link or NULL </returns>
//////////////////////////////////////////////////////////////////////
public AtomLink FindService(string service, string type)
{
foreach (AtomLink link in List)
{
string linkRel = link.Rel;
string linkType = link.Type;
if ((service == null || (linkRel != null && linkRel == service)) &&
(type == null || (linkType != null && linkType.StartsWith(type))))
{
return link;
}
}
return null;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>public AtomLink FindService(string service,string type)
/// Retrieves the first link with the supplied 'rel' and/or 'type' value.
/// If either parameter is null, the corresponding match isn't needed.
/// </summary>
/// <param name="service">the service entry to find</param>
/// <param name="type">the link type to find</param>
/// <returns>the found link or NULL </returns>
//////////////////////////////////////////////////////////////////////
public List<AtomLink> FindServiceList(string service, string type)
{
List<AtomLink> foundLinks = new List<AtomLink>();
foreach (AtomLink link in List)
{
string linkRel = link.Rel;
string linkType = link.Type;
if ((service == null || (linkRel != null && linkRel == service)) &&
(type == null || (linkType != null && linkType == type)))
{
foundLinks.Add(link);
}
}
return foundLinks;
}
/////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>standard typed collection based on 1.1 framework for AtomCategory
/// </summary>
//////////////////////////////////////////////////////////////////////
public class AtomCategoryCollection : AtomCollectionBase<AtomCategory>
{
/// <summary>standard typed accessor method </summary>
public override void Add(AtomCategory value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
// Remove category with the same term to avoid duplication.
AtomCategory oldCategory = Find(value.Term, value.Scheme);
if (oldCategory != null)
{
Remove(oldCategory);
}
base.Add(value);
}
/// <summary>
/// finds the first category with this term
/// ignoring schemes
/// </summary>
/// <param name="term">the category term to search for</param>
/// <returns>AtomCategory</returns>
public AtomCategory Find(string term)
{
return Find(term, null);
}
/// <summary>
/// finds a category with a given term and scheme
/// </summary>
/// <param name="term"></param>
/// <param name="scheme"></param>
/// <returns>AtomCategory or NULL</returns>
public AtomCategory Find(string term, AtomUri scheme)
{
foreach (AtomCategory category in List)
{
if (scheme == null || scheme == category.Scheme)
{
if (term == category.Term)
{
return category;
}
}
}
return null;
}
/// <summary>standard typed accessor method </summary>
public override bool Contains(AtomCategory value)
{
if (value == null)
{
return (List.Contains(value));
}
// If value is not of type AtomCategory, this will return false.
if (Find(value.Term, value.Scheme) != null)
{
return true;
}
return false;
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>standard typed collection based on 1.1 framework for AtomPerson
/// </summary>
//////////////////////////////////////////////////////////////////////
public class QueryCategoryCollection : AtomCollectionBase<QueryCategory>
{
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>standard typed collection based on 1.1 framework for AtomPerson
/// </summary>
//////////////////////////////////////////////////////////////////////
public class AtomPersonCollection : AtomCollectionBase<AtomPerson>
{
}
/////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Generic collection base class
/// </summary>
/// <typeparam name="T"></typeparam>
public class AtomCollectionBase<T> : IList<T>
{
/// <summary>
/// the internal list object that is used
/// </summary>
protected List<T> List = new List<T>();
/// <summary>standard typed accessor method </summary>
public virtual T this[int index]
{
get { return List[index]; }
set { List[index] = value; }
}
/// <summary>standard typed accessor method </summary>
public virtual void Add(T value)
{
List.Add(value);
}
/// <summary>
/// default overload, see base class
/// </summary>
/// <param name="index"></param>
public virtual void RemoveAt(int index)
{
List.RemoveAt(index);
}
/// <summary>
/// default overload, see base class
/// </summary>
public virtual void Clear()
{
List.Clear();
}
/// <summary>
/// default overload, see base class
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public virtual void CopyTo(T[] arr, int index)
{
List.CopyTo(arr, index);
}
/// <summary>standard typed accessor method </summary>
/// <param name="value"></param>
public virtual int IndexOf(T value)
{
return (List.IndexOf(value));
}
/// <summary>standard typed accessor method </summary>
/// <param name="index"></param>
/// <param name="value"></param>
public virtual void Insert(int index, T value)
{
List.Insert(index, value);
}
/// <summary>standard typed accessor method </summary>
/// <param name="value"></param>
public virtual bool Remove(T value)
{
return List.Remove(value);
}
/// <summary>standard typed accessor method </summary>
/// <param name="value"></param>
public virtual bool Contains(T value)
{
// If value is not of type AtomPerson, this will return false.
return (List.Contains(value));
}
/// <summary>
/// default overload, see base class
/// </summary>
public virtual int Count
{
get { return List.Count; }
}
/// <summary>
/// default overload, see base class
/// </summary>
public virtual bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// default overload, see base class
/// </summary>
public IEnumerator<T> GetEnumerator()
{
return List.GetEnumerator();
}
/// <summary>
/// default overload, see base class
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return List.GetEnumerator();
}
}
/// <summary>
/// internal list to override the add and the constructor
/// </summary>
/// <returns></returns>
public class ExtensionList : IList<IExtensionElementFactory>
{
private readonly List<IExtensionElementFactory> _list = new List<IExtensionElementFactory>();
private readonly IVersionAware container;
/// <summary>
/// returns an extensionlist that belongs to a version aware
/// container
/// </summary>
/// <param name="container"></param>
public ExtensionList(IVersionAware container)
{
this.container = container;
}
/// <summary>
/// default overload, see base class
/// </summary>
/// <param name="item"></param>
public int IndexOf(IExtensionElementFactory item)
{
return _list.IndexOf(item);
}
/// <summary>
/// default overload, see base class
/// </summary>
/// <param name="index"></param>
/// <param name="item"></param>
public void Insert(int index, IExtensionElementFactory item)
{
_list.Insert(index, item);
}
/// <summary>
/// default overload, see base class
/// </summary>
/// <param name="index"></param>
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
/// <summary>
/// default overload, see base class
/// </summary>
/// <param name="index"></param>
public IExtensionElementFactory this[int index]
{
get { return _list[index]; }
set { _list[index] = value; }
}
/// <summary>
/// default overload, see base class
/// </summary>
/// <param name="item"></param>
void ICollection<IExtensionElementFactory>.Add(IExtensionElementFactory item)
{
Add(item);
}
/// <summary>
/// default overload, see base class
/// </summary>
public void Clear()
{
_list.Clear();
}
/// <summary>
/// default overload, see base class
/// </summary>
/// <param name="item"></param>
public bool Contains(IExtensionElementFactory item)
{
return _list.Contains(item);
}
/// <summary>
/// default overload, see base class
/// </summary>
/// <param name="array"></param>
/// <param name="arrayIndex"></param>
public void CopyTo(IExtensionElementFactory[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
/// <summary>
/// default overload, see base class
/// </summary>
public int Count
{
get { return _list.Count; }
}
/// <summary>
/// default overload, see base class
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// default overload, see base class
/// </summary>
/// <param name="item"></param>
public bool Remove(IExtensionElementFactory item)
{
return _list.Remove(item);
}
/// <summary>
/// default overload, see base class
/// </summary>
public IEnumerator<IExtensionElementFactory> GetEnumerator()
{
return _list.GetEnumerator();
}
/// <summary>
/// default overload, see base class
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
/// <summary>
/// Return a new collection that is not version aware.
/// </summary>
public static ExtensionList NotVersionAware()
{
return new ExtensionList(NullVersionAware.Instance);
}
/// <summary>
/// adds value to the extensionlist.
/// </summary>
/// <param name="value"></param>
/// <returns>returns the positin in the list after the add</returns>
public int Add(IExtensionElementFactory value)
{
IVersionAware target = value as IVersionAware;
if (target != null)
{
target.ProtocolMajor = container.ProtocolMajor;
target.ProtocolMinor = container.ProtocolMinor;
}
if (value != null)
{
_list.Add(value);
}
return _list.Count - 1;
//return _list.IndexOf(value);
}
/// <summary>
/// removes a factory defined by namespace and local name
/// </summary>
/// <param name="ns">namespace of the factory</param>
/// <param name="name">local name of the factory</param>
public bool Remove(string ns, string name)
{
for (int i = 0; i < _list.Count; i++)
{
if (_list[i].XmlNameSpace == ns && _list[i].XmlName == name)
{
_list.RemoveAt(i);
return true;
}
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
using System;
using UnityEngine.VR.WSA;
namespace HoloToolkit.Unity.InputModule
{
/// <summary>
/// Component that allows dragging an object with your hand on HoloLens.
/// Dragging is done by calculating the angular delta and z-delta between the current and previous hand positions,
/// and then repositioning the object based on that.
/// </summary>
public class HandDraggable : MonoBehaviour,
IFocusable,
IInputHandler,
ISourceStateHandler
{
/// <summary>
/// Event triggered when dragging starts.
/// </summary>
public event Action StartedDragging;
/// <summary>
/// Event triggered when dragging stops.
/// </summary>
public event Action StoppedDragging;
[Tooltip("Transform that will be dragged. Defaults to the object of the component.")]
public Transform HostTransform;
[Tooltip("Scale by which hand movement in z is multipled to move the dragged object.")]
public float DistanceScale = 2f;
public enum RotationModeEnum
{
Default,
LockObjectRotation,
OrientTowardUser,
OrientTowardUserAndKeepUpright
}
public RotationModeEnum RotationMode = RotationModeEnum.Default;
[Tooltip("Controls the speed at which the object will interpolate toward the desired position")]
[Range(0.01f, 1.0f)]
public float PositionLerpSpeed = 0.2f;
[Tooltip("Controls the speed at which the object will interpolate toward the desired rotation")]
[Range(0.01f, 1.0f)]
public float RotationLerpSpeed = 0.2f;
public bool IsDraggingEnabled = true;
private Camera mainCamera;
private bool isDragging;
private bool isGazed;
private Vector3 objRefForward;
private Vector3 objRefUp;
private float objRefDistance;
private Quaternion gazeAngularOffset;
private float handRefDistance;
private Vector3 objRefGrabPoint;
private Vector3 draggingPosition;
private Quaternion draggingRotation;
private IInputSource currentInputSource = null;
private uint currentInputSourceId;
private void Start()
{
if (HostTransform == null)
{
HostTransform = transform;
}
mainCamera = Camera.main;
}
private void OnDestroy()
{
if (isDragging)
{
StopDragging();
}
if (isGazed)
{
OnFocusExit();
}
}
private void Update()
{
if (IsDraggingEnabled && isDragging)
{
UpdateDragging();
}
}
/// <summary>
/// Starts dragging the object.
/// </summary>
public void StartDragging()
{
if (!IsDraggingEnabled)
{
return;
}
if (isDragging)
{
return;
}
// Add self as a modal input handler, to get all inputs during the manipulation
InputManager.Instance.PushModalInputHandler(gameObject);
isDragging = true;
//GazeCursor.Instance.SetState(GazeCursor.State.Move);
//GazeCursor.Instance.SetTargetObject(HostTransform);
Vector3 gazeHitPosition = GazeManager.Instance.HitInfo.point;
Vector3 handPosition;
currentInputSource.TryGetPosition(currentInputSourceId, out handPosition);
Vector3 pivotPosition = GetHandPivotPosition();
handRefDistance = Vector3.Magnitude(handPosition - pivotPosition);
objRefDistance = Vector3.Magnitude(gazeHitPosition - pivotPosition);
Vector3 objForward = HostTransform.forward;
Vector3 objUp = HostTransform.up;
// Store where the object was grabbed from
objRefGrabPoint = mainCamera.transform.InverseTransformDirection(HostTransform.position - gazeHitPosition);
Vector3 objDirection = Vector3.Normalize(gazeHitPosition - pivotPosition);
Vector3 handDirection = Vector3.Normalize(handPosition - pivotPosition);
objForward = mainCamera.transform.InverseTransformDirection(objForward); // in camera space
objUp = mainCamera.transform.InverseTransformDirection(objUp); // in camera space
objDirection = mainCamera.transform.InverseTransformDirection(objDirection); // in camera space
handDirection = mainCamera.transform.InverseTransformDirection(handDirection); // in camera space
objRefForward = objForward;
objRefUp = objUp;
// Store the initial offset between the hand and the object, so that we can consider it when dragging
gazeAngularOffset = Quaternion.FromToRotation(handDirection, objDirection);
draggingPosition = gazeHitPosition;
// destroy existing anchor
DestroyImmediate(this.gameObject.GetComponent<WorldAnchor>());
StartedDragging.RaiseEvent();
}
/// <summary>
/// Gets the pivot position for the hand, which is approximated to the base of the neck.
/// </summary>
/// <returns>Pivot position for the hand.</returns>
private Vector3 GetHandPivotPosition()
{
Vector3 pivot = Camera.main.transform.position + new Vector3(0, -0.2f, 0) - Camera.main.transform.forward * 0.2f; // a bit lower and behind
return pivot;
}
/// <summary>
/// Enables or disables dragging.
/// </summary>
/// <param name="isEnabled">Indicates whether dragging shoudl be enabled or disabled.</param>
public void SetDragging(bool isEnabled)
{
if (IsDraggingEnabled == isEnabled)
{
return;
}
IsDraggingEnabled = isEnabled;
if (isDragging)
{
StopDragging();
}
}
/// <summary>
/// Update the position of the object being dragged.
/// </summary>
private void UpdateDragging()
{
Vector3 newHandPosition;
currentInputSource.TryGetPosition(currentInputSourceId, out newHandPosition);
Vector3 pivotPosition = GetHandPivotPosition();
Vector3 newHandDirection = Vector3.Normalize(newHandPosition - pivotPosition);
newHandDirection = mainCamera.transform.InverseTransformDirection(newHandDirection); // in camera space
Vector3 targetDirection = Vector3.Normalize(gazeAngularOffset * newHandDirection);
targetDirection = mainCamera.transform.TransformDirection(targetDirection); // back to world space
float currenthandDistance = Vector3.Magnitude(newHandPosition - pivotPosition);
float distanceRatio = currenthandDistance / handRefDistance;
float distanceOffset = distanceRatio > 0 ? (distanceRatio - 1f) * DistanceScale : 0;
float targetDistance = objRefDistance + distanceOffset;
draggingPosition = pivotPosition + (targetDirection * targetDistance);
if (RotationMode == RotationModeEnum.OrientTowardUser || RotationMode == RotationModeEnum.OrientTowardUserAndKeepUpright)
{
draggingRotation = Quaternion.LookRotation(HostTransform.position - pivotPosition);
}
else if (RotationMode == RotationModeEnum.LockObjectRotation)
{
draggingRotation = HostTransform.rotation;
}
else // RotationModeEnum.Default
{
Vector3 objForward = mainCamera.transform.TransformDirection(objRefForward); // in world space
Vector3 objUp = mainCamera.transform.TransformDirection(objRefUp); // in world space
draggingRotation = Quaternion.LookRotation(objForward, objUp);
}
// Apply Final Position
HostTransform.position = Vector3.Lerp(HostTransform.position, draggingPosition + mainCamera.transform.TransformDirection(objRefGrabPoint), PositionLerpSpeed);
// Apply Final Rotation
HostTransform.rotation = Quaternion.Lerp(HostTransform.rotation, draggingRotation, RotationLerpSpeed);
if (RotationMode == RotationModeEnum.OrientTowardUserAndKeepUpright)
{
Quaternion upRotation = Quaternion.FromToRotation(HostTransform.up, Vector3.up);
HostTransform.rotation = upRotation * HostTransform.rotation;
}
}
/// <summary>
/// Stops dragging the object.
/// </summary>
public void StopDragging()
{
if (!isDragging)
{
return;
}
// Remove self as a modal input handler
InputManager.Instance.PopModalInputHandler();
isDragging = false;
currentInputSource = null;
StoppedDragging.RaiseEvent();
// Restore the world anchor
SendMessageUpwards("OnAddAnchor", this.gameObject);
}
public void OnFocusEnter()
{
if (!IsDraggingEnabled)
{
return;
}
if (isGazed)
{
return;
}
isGazed = true;
}
public void OnFocusExit()
{
if (!IsDraggingEnabled)
{
return;
}
if (!isGazed)
{
return;
}
isGazed = false;
}
public void OnInputUp(InputEventData eventData)
{
if (currentInputSource != null &&
eventData.SourceId == currentInputSourceId)
{
StopDragging();
}
}
public void OnInputDown(InputEventData eventData)
{
if (isDragging)
{
// We're already handling drag input, so we can't start a new drag operation.
return;
}
if (!eventData.InputSource.SupportsInputInfo(eventData.SourceId, SupportedInputInfo.Position))
{
// The input source must provide positional data for this script to be usable
return;
}
currentInputSource = eventData.InputSource;
currentInputSourceId = eventData.SourceId;
StartDragging();
}
public void OnSourceDetected(SourceStateEventData eventData)
{
// Nothing to do
}
public void OnSourceLost(SourceStateEventData eventData)
{
if (currentInputSource != null && eventData.SourceId == currentInputSourceId)
{
StopDragging();
}
}
}
}
| |
// <copyright file="Evaluate.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <contribution>
// CERN - European Laboratory for Particle Physics
// http://www.docjar.com/html/api/cern/jet/math/Bessel.java.html
// Copyright 1999 CERN - European Laboratory for Particle Physics.
// Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose
// is hereby granted without fee, provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear in supporting documentation.
// CERN makes no representations about the suitability of this software for any purpose.
// It is provided "as is" without expressed or implied warranty.
// TOMS757 - Uncommon Special Functions (Fortran77) by Allan McLeod
// http://people.sc.fsu.edu/~jburkardt/f77_src/toms757/toms757.html
// Wei Wu
// Cephes Math Library, Stephen L. Moshier
// ALGLIB 2.0.1, Sergey Bochkanov
// </contribution>
// ReSharper disable CheckNamespace
namespace MathNet.Numerics
// ReSharper restore CheckNamespace
{
using System;
#if !NOSYSNUMERICS
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Evaluation functions, useful for function approximation.
/// </summary>
public static class Evaluate
{
/// <summary>
/// Evaluate a polynomial at point x.
/// Coefficients are ordered by power with power k at index k.
/// Example: coefficients [3,-1,2] represent y=2x^2-x+3.
/// </summary>
/// <param name="z">The location where to evaluate the polynomial at.</param>
/// <param name="coefficients">The coefficients of the polynomial, coefficient for power k at index k.</param>
public static double Polynomial(double z, params double[] coefficients)
{
double sum = coefficients[coefficients.Length - 1];
for (int i = coefficients.Length - 2; i >= 0; --i)
{
sum *= z;
sum += coefficients[i];
}
return sum;
}
/// <summary>
/// Evaluate a polynomial at point x.
/// Coefficients are ordered by power with power k at index k.
/// Example: coefficients [3,-1,2] represent y=2x^2-x+3.
/// </summary>
/// <param name="z">The location where to evaluate the polynomial at.</param>
/// <param name="coefficients">The coefficients of the polynomial, coefficient for power k at index k.</param>
public static Complex Polynomial(Complex z, params double[] coefficients)
{
Complex sum = coefficients[coefficients.Length - 1];
for (int i = coefficients.Length - 2; i >= 0; --i)
{
sum *= z;
sum += coefficients[i];
}
return sum;
}
/// <summary>
/// Evaluate a polynomial at point x.
/// Coefficients are ordered by power with power k at index k.
/// Example: coefficients [3,-1,2] represent y=2x^2-x+3.
/// </summary>
/// <param name="z">The location where to evaluate the polynomial at.</param>
/// <param name="coefficients">The coefficients of the polynomial, coefficient for power k at index k.</param>
public static Complex Polynomial(Complex z, params Complex[] coefficients)
{
Complex sum = coefficients[coefficients.Length - 1];
for (int i = coefficients.Length - 2; i >= 0; --i)
{
sum *= z;
sum += coefficients[i];
}
return sum;
}
/// <summary>
/// Numerically stable series summation
/// </summary>
/// <param name="nextSummand">provides the summands sequentially</param>
/// <returns>Sum</returns>
internal static double Series(Func<double> nextSummand)
{
double compensation = 0.0;
double current;
const double factor = 1 << 16;
double sum = nextSummand();
do
{
// Kahan Summation
// NOTE (ruegg): do NOT optimize. Now, how to tell that the compiler?
current = nextSummand();
double y = current - compensation;
double t = sum + y;
compensation = t - sum;
compensation -= y;
sum = t;
}
while (Math.Abs(sum) < Math.Abs(factor * current));
return sum;
}
/// <summary> Evaluates the series of Chebyshev polynomials Ti at argument x/2.
/// The series is given by
/// <pre>
/// N-1
/// - '
/// y = > coef[i] T (x/2)
/// - i
/// i=0
/// </pre>
/// Coefficients are stored in reverse order, i.e. the zero
/// order term is last in the array. Note N is the number of
/// coefficients, not the order.
/// <p/>
/// If coefficients are for the interval a to b, x must
/// have been transformed to x -> 2(2x - b - a)/(b-a) before
/// entering the routine. This maps x from (a, b) to (-1, 1),
/// over which the Chebyshev polynomials are defined.
/// <p/>
/// If the coefficients are for the inverted interval, in
/// which (a, b) is mapped to (1/b, 1/a), the transformation
/// required is x -> 2(2ab/x - b - a)/(b-a). If b is infinity,
/// this becomes x -> 4a/x - 1.
/// <p/>
/// SPEED:
/// <p/>
/// Taking advantage of the recurrence properties of the
/// Chebyshev polynomials, the routine requires one more
/// addition per loop than evaluating a nested polynomial of
/// the same degree.
/// </summary>
/// <param name="coefficients">The coefficients of the polynomial.</param>
/// <param name="x">Argument to the polynomial.</param>
/// <remarks>
/// Reference: https://bpm2.svn.codeplex.com/svn/Common.Numeric/Arithmetic.cs
/// <p/>
/// Marked as Deprecated in
/// http://people.apache.org/~isabel/mahout_site/mahout-matrix/apidocs/org/apache/mahout/jet/math/Arithmetic.html
/// </remarks>
internal static double ChebyshevA(double[] coefficients, double x)
{
// TODO: Unify, normalize, then make public
double b2;
int p = 0;
double b0 = coefficients[p++];
double b1 = 0.0;
int i = coefficients.Length - 1;
do
{
b2 = b1;
b1 = b0;
b0 = x * b1 - b2 + coefficients[p++];
}
while (--i > 0);
return 0.5 * (b0 - b2);
}
/// <summary>
/// Summation of Chebyshev polynomials, using the Clenshaw method with Reinsch modification.
/// </summary>
/// <param name="n">The no. of terms in the sequence.</param>
/// <param name="coefficients">The coefficients of the Chebyshev series, length n+1.</param>
/// <param name="x">The value at which the series is to be evaluated.</param>
/// <remarks>
/// ORIGINAL AUTHOR:
/// Dr. Allan J. MacLeod; Dept. of Mathematics and Statistics, University of Paisley; High St., PAISLEY, SCOTLAND
/// REFERENCES:
/// "An error analysis of the modified Clenshaw method for evaluating Chebyshev and Fourier series"
/// J. Oliver, J.I.M.A., vol. 20, 1977, pp379-391
/// </remarks>
internal static double ChebyshevSum(int n, double[] coefficients, double x)
{
// TODO: Unify, normalize, then make public
// If |x| < 0.6 use the standard Clenshaw method
if (Math.Abs(x) < 0.6)
{
double u0 = 0.0;
double u1 = 0.0;
double u2 = 0.0;
double xx = x + x;
for (int i = n; i >= 0; i--)
{
u2 = u1;
u1 = u0;
u0 = xx * u1 + coefficients[i] - u2;
}
return (u0 - u2) / 2.0;
}
// If ABS ( T ) > = 0.6 use the Reinsch modification
// T > = 0.6 code
if (x > 0.0)
{
double u1 = 0.0;
double d1 = 0.0;
double d2 = 0.0;
double xx = (x - 0.5) - 0.5;
xx = xx + xx;
for (int i = n; i >= 0; i--)
{
d2 = d1;
double u2 = u1;
d1 = xx * u2 + coefficients[i] + d2;
u1 = d1 + u2;
}
return (d1 + d2) / 2.0;
}
else
{
// T < = -0.6 code
double u1 = 0.0;
double d1 = 0.0;
double d2 = 0.0;
double xx = (x + 0.5) + 0.5;
xx = xx + xx;
for (int i = n; i >= 0; i--)
{
d2 = d1;
double u2 = u1;
d1 = xx * u2 + coefficients[i] - d2;
u1 = d1 - u2;
}
return (d1 - d2) / 2.0;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace BatchClientIntegrationTests
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatchTestCommon;
using Fixtures;
using Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Common;
using IntegrationTestCommon;
using IntegrationTestUtilities;
using Microsoft.Azure.Batch.Protocol.BatchRequests;
using Microsoft.Azure.Batch.Auth;
using Microsoft.Azure.Batch.Integration.Tests.Infrastructure;
using Microsoft.Rest.Azure;
using Xunit;
using Xunit.Abstractions;
using Protocol = Microsoft.Azure.Batch.Protocol;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
public class CloudPoolIntegrationTests
{
private readonly ITestOutputHelper testOutputHelper;
private static readonly TimeSpan LongTestTimeout = TimeSpan.FromMinutes(5);
private static readonly TimeSpan TestTimeout = TimeSpan.FromMinutes(1);
public CloudPoolIntegrationTests(ITestOutputHelper testOutputHelper)
{
this.testOutputHelper = testOutputHelper;
//Note -- this class does not and should not need a pool fixture
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public async Task PoolPatch()
{
Func<Task> test = async () =>
{
using (BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync().ConfigureAwait(false))
{
string poolId = "TestPatchPool-" + TestUtilities.GetMyName();
const string metadataKey = "Foo";
const string metadataValue = "Bar";
const string startTaskCommandLine = "cmd /c dir";
try
{
CloudPool pool = batchCli.PoolOperations.CreatePool(
poolId,
PoolFixture.VMSize,
new CloudServiceConfiguration(PoolFixture.OSFamily),
targetDedicatedComputeNodes: 0);
await pool.CommitAsync().ConfigureAwait(false);
await pool.RefreshAsync().ConfigureAwait(false);
pool.StartTask = new StartTask(startTaskCommandLine);
pool.Metadata = new List<MetadataItem>()
{
new MetadataItem(metadataKey, metadataValue)
};
await pool.CommitChangesAsync().ConfigureAwait(false);
await pool.RefreshAsync().ConfigureAwait(false);
Assert.Equal(startTaskCommandLine, pool.StartTask.CommandLine);
Assert.Equal(metadataKey, pool.Metadata.Single().Name);
Assert.Equal(metadataValue, pool.Metadata.Single().Value);
}
finally
{
await TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).ConfigureAwait(false);
}
}
};
await SynchronizationContextHelper.RunTestAsync(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void Bug1505248SupportMultipleTasksPerComputeNodeOnPoolAndPoolUserSpec()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
// create a pool with the two new props
string poolId = "Bug1505248SupportMultipleTasksPerComputeNode-pool-" + TestUtilities.GetMyName();
try
{
CloudPool newPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0);
newPool.MaxTasksPerComputeNode = 3;
newPool.TaskSchedulingPolicy =
new TaskSchedulingPolicy(Microsoft.Azure.Batch.Common.ComputeNodeFillType.Pack);
newPool.Commit();
CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId);
Assert.Equal(3, boundPool.MaxTasksPerComputeNode);
Assert.Equal(ComputeNodeFillType.Pack, boundPool.TaskSchedulingPolicy.ComputeNodeFillType);
}
finally
{
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
string jobId = "Bug1505248SupportMultipleTasksPerComputeNode-Job-" + TestUtilities.GetMyName();
try
{
// create a job with new props set on pooluserspec
{
CloudJob unboundJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation());
AutoPoolSpecification unboundAPS = new AutoPoolSpecification();
PoolSpecification unboundPS = new PoolSpecification();
unboundJob.PoolInformation.AutoPoolSpecification = unboundAPS;
unboundAPS.PoolSpecification = unboundPS;
unboundPS.MaxTasksPerComputeNode = 3;
unboundAPS.PoolSpecification.TargetDedicatedComputeNodes = 0; // don't use up compute nodes for this test
unboundPS.TaskSchedulingPolicy = new TaskSchedulingPolicy(Microsoft.Azure.Batch.Common.ComputeNodeFillType.Pack);
// required but unrelated to test
unboundPS.VirtualMachineSize = PoolFixture.VMSize;
unboundPS.CloudServiceConfiguration = new CloudServiceConfiguration(PoolFixture.OSFamily);
unboundAPS.PoolLifetimeOption = Microsoft.Azure.Batch.Common.PoolLifetimeOption.Job;
unboundJob.Commit();
}
// confirm props were set
CloudJob boundJob = batchCli.JobOperations.GetJob(jobId);
PoolInformation poolInformation = boundJob.PoolInformation;
AutoPoolSpecification boundAPS = poolInformation.AutoPoolSpecification;
PoolSpecification boundPUS = boundAPS.PoolSpecification;
Assert.Equal(3, boundPUS.MaxTasksPerComputeNode);
Assert.Equal(ComputeNodeFillType.Pack, boundPUS.TaskSchedulingPolicy.ComputeNodeFillType);
// change the props
//TODO: Possible change this test to use a JobSchedule here?
//boundPUS.MaxTasksPerComputeNode = 2;
//boundPUS.TaskSchedulingPolicy = new TaskSchedulingPolicy(Microsoft.Azure.Batch.Common.ComputeNodeFillType.Spread);
//boundJob.Commit();
//boundJob.Refresh();
//boundAPS = boundJob.PoolInformation.AutoPoolSpecification;
//boundPUS = boundAPS.PoolSpecification;
//Debug.Assert(2 == boundPUS.MaxTasksPerComputeNode);
//Debug.Assert(Microsoft.Azure.Batch.Common.ComputeNodeFillType.Spread == boundPUS.TaskSchedulingPolicy.ComputeNodeFillType);
}
finally
{
TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)]
public void Bug1587303StartTaskResourceFilesNotPushedToServer()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string poolId = "Bug1587303Pool-" + TestUtilities.GetMyName();
const string resourceFileSas = "http://azure.com";
const string resourceFileValue = "count0ResFiles.exe";
const string envSettingName = "envName";
const string envSettingValue = "envValue";
try
{
// create a pool with env-settings and ResFiles
{
CloudPool myPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0);
StartTask st = new StartTask("dir");
MakeResourceFiles(st, resourceFileSas, resourceFileValue);
AddEnviornmentSettingsToStartTask(st, envSettingName, envSettingValue);
// set the pool's start task so the collections get pushed
myPool.StartTask = st;
myPool.Commit();
}
// confirm pool has correct values
CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId);
CheckResourceFiles(boundPool.StartTask, resourceFileSas, resourceFileValue);
CheckEnvironmentSettingsOnStartTask(boundPool.StartTask, envSettingName, envSettingValue);
// clear the collections
boundPool.StartTask.EnvironmentSettings = null;
boundPool.StartTask.ResourceFiles = null;
boundPool.Commit();
boundPool.Refresh();
StartTask boundST = boundPool.StartTask;
// confirm the collections are cleared/null
Assert.Null(boundST.ResourceFiles);
Assert.Null(boundST.EnvironmentSettings);
// set the collections again
MakeResourceFiles(boundST, resourceFileSas, resourceFileValue);
AddEnviornmentSettingsToStartTask(boundST, envSettingName, envSettingValue);
boundPool.Commit();
boundPool.Refresh();
// confirm the collectsion are correctly re-established
CheckResourceFiles(boundPool.StartTask, resourceFileSas, resourceFileValue);
CheckEnvironmentSettingsOnStartTask(boundPool.StartTask, envSettingName, envSettingValue);
//set collections to empty-but-non-null collections
IList<ResourceFile> emptyResfiles = new List<ResourceFile>();
IList<EnvironmentSetting> emptyEnvSettings = new List<EnvironmentSetting>();
boundPool.StartTask.EnvironmentSettings = emptyEnvSettings;
boundPool.StartTask.ResourceFiles = emptyResfiles;
boundPool.Commit();
boundPool.Refresh();
boundST = boundPool.StartTask;
var count0ResFiles = boundPool.StartTask.ResourceFiles;
var count0EnvSettings = boundPool.StartTask.EnvironmentSettings;
// confirm that the collections are non-null and have count-0
Assert.NotNull(count0ResFiles);
Assert.NotNull(count0EnvSettings);
Assert.Empty(count0ResFiles);
Assert.Empty(count0EnvSettings);
//clean up
boundPool.Delete();
System.Threading.Thread.Sleep(5000); // wait for pool to be deleted
// check pool create with empty-but-non-null collections
{
CloudPool myPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0);
StartTask st = new StartTask("dir");
// use the empty collections from above
st.ResourceFiles = emptyResfiles;
st.EnvironmentSettings = emptyEnvSettings;
// set the pool's start task so the collections get pushed
myPool.StartTask = st;
myPool.Commit();
}
boundPool = batchCli.PoolOperations.GetPool(poolId);
boundST = boundPool.StartTask;
count0ResFiles = boundPool.StartTask.ResourceFiles;
count0EnvSettings = boundPool.StartTask.EnvironmentSettings;
// confirm that the collections are non-null and have count-0
Assert.NotNull(count0ResFiles);
Assert.NotNull(count0EnvSettings);
Assert.Empty(count0ResFiles);
Assert.Empty(count0EnvSettings);
}
finally
{
// cleanup
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)]
public void Bug1433123PoolMissingResizeTimeout()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string poolId = "Bug1433123PoolMissingResizeTimeout-" + TestUtilities.GetMyName();
try
{
TimeSpan referenceRST = TimeSpan.FromMinutes(5);
// create a pool with env-settings and ResFiles
{
CloudPool myPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0);
// set the reference value
myPool.ResizeTimeout = referenceRST;
myPool.Commit();
}
// confirm pool has correct values
CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId);
// confirm value is correct
Assert.Equal(referenceRST, boundPool.ResizeTimeout);
// confirm constraint does not allow changes to bound object
TestUtilities.AssertThrows<InvalidOperationException>(() => boundPool.ResizeTimeout = TimeSpan.FromMinutes(1));
}
finally
{
// cleanup
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void Bug1656475PoolLifetimeOption()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string jsId = "Bug1656475PoolLifetimeOption-" + TestUtilities.GetMyName();
try
{
{
CloudJobSchedule unboundJobSchedule = batchCli.JobScheduleOperations.CreateJobSchedule();
unboundJobSchedule.Schedule = new Schedule() { RecurrenceInterval = TimeSpan.FromMinutes(10) };
unboundJobSchedule.Id = jsId;
AutoPoolSpecification iaps = new AutoPoolSpecification();
// test that it can be read from unbound/unset object
PoolLifetimeOption defaultVal = iaps.PoolLifetimeOption;
// test it can be set on unbound and read back
iaps.PoolLifetimeOption = PoolLifetimeOption.JobSchedule;
// read it back and confirm value
Assert.Equal(PoolLifetimeOption.JobSchedule, iaps.PoolLifetimeOption);
unboundJobSchedule.JobSpecification = new JobSpecification(new PoolInformation() { AutoPoolSpecification = iaps });
// make ias viable for adding the wi
iaps.AutoPoolIdPrefix = Microsoft.Azure.Batch.Constants.DefaultConveniencePrefix + TestUtilities.GetMyName();
PoolSpecification ips = new PoolSpecification();
iaps.PoolSpecification = ips;
ips.TargetDedicatedComputeNodes = 0;
ips.VirtualMachineSize = PoolFixture.VMSize;
ips.CloudServiceConfiguration = new CloudServiceConfiguration(PoolFixture.OSFamily);
unboundJobSchedule.Commit();
}
CloudJobSchedule boundJobSchedule = batchCli.JobScheduleOperations.GetJobSchedule(jsId);
// confirm the PLO is set correctly on bound WI
Assert.NotNull(boundJobSchedule);
Assert.NotNull(boundJobSchedule.JobSpecification);
Assert.NotNull(boundJobSchedule.JobSpecification.PoolInformation);
Assert.NotNull(boundJobSchedule.JobSpecification.PoolInformation.AutoPoolSpecification);
AutoPoolSpecification boundIAPS = boundJobSchedule.JobSpecification.PoolInformation.AutoPoolSpecification;
Assert.Equal(PoolLifetimeOption.JobSchedule, boundIAPS.PoolLifetimeOption);
// in phase 1 PLO is read-only on bound WI/APS so no tests to change it here
}
finally
{
// cleanup
TestUtilities.DeleteJobScheduleIfExistsAsync(batchCli, jsId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongDuration)]
public void Bug1432812SetAutoScaleMissingOnPoolPoolMgr()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string poolId = "Bug1432812-" + TestUtilities.GetMyName();
const string poolASFormulaOrig = "$TargetDedicatedNodes=0;";
const string poolASFormula2 = "$TargetDedicatedNodes=1;";
// craft exactly how it would be returned by Evaluate so indexof can work
try
{
// create a pool.. empty for now
{
CloudPool unboundPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily));
unboundPool.AutoScaleEnabled = true;
unboundPool.AutoScaleFormula = poolASFormulaOrig;
unboundPool.Commit();
TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromSeconds(20)).Wait();
}
// EvaluteAutoScale
CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId);
Assert.True(boundPool.AutoScaleEnabled.HasValue);
Assert.True(boundPool.AutoScaleEnabled.Value);
Assert.Equal(poolASFormulaOrig, boundPool.AutoScaleFormula);
AutoScaleRun eval = boundPool.EvaluateAutoScale(poolASFormula2);
Assert.Contains(poolASFormula2, eval.Results);
// DisableAutoScale
boundPool.DisableAutoScale();
boundPool.Refresh();
// autoscale should be disabled now
Assert.True(boundPool.AutoScaleEnabled.HasValue);
Assert.False(boundPool.AutoScaleEnabled.Value);
// EnableAutoScale
TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(5)).Wait();
boundPool.EnableAutoScale(poolASFormula2);
boundPool.Refresh();
// confirm is enabled and formula has correct value
Assert.True(boundPool.AutoScaleEnabled.HasValue);
Assert.True(boundPool.AutoScaleEnabled.Value);
Assert.Equal(poolASFormula2, boundPool.AutoScaleFormula);
}
finally
{
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, LongTestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void Bug1432819UpdateImplOnCloudPool()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string poolId = "Bug1432819-" + TestUtilities.GetMyName();
try
{
CloudPool unboundPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0);
unboundPool.Commit();
CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId);
IList<MetadataItem> changedMDI = new List<MetadataItem> { new MetadataItem("name", "value") };
boundPool.Metadata = changedMDI;
boundPool.Commit();
CloudPool boundPool2 = batchCli.PoolOperations.GetPool(poolId);
Assert.NotNull(boundPool2.Metadata);
// confirm the pool was updated
foreach (MetadataItem curMDI in boundPool2.Metadata)
{
Assert.Equal("name", curMDI.Name);
Assert.Equal("value", curMDI.Value);
}
}
finally
{
// cleanup
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void TestListPoolUsageMetrics()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
// test via faking data
DateTime endTime = DateTime.UtcNow.AddYears(-1);
DateTime startTime = DateTime.UtcNow;
const int totalCoreHours = 1;
const string virtualMachineSize = "really really big";
List<Protocol.Models.PoolUsageMetrics> pums = new List<Protocol.Models.PoolUsageMetrics>();
// create some data to return
for (int i = 0; i < 4; i++)
{
string id = "my fancy pool id " + i.ToString();
Protocol.Models.PoolUsageMetrics newPum = new Protocol.Models.PoolUsageMetrics()
{
PoolId = id,
EndTime = endTime,
StartTime = startTime,
TotalCoreHours = totalCoreHours,
VmSize = virtualMachineSize
};
pums.Add(newPum);
}
// our injector of fake data
TestListPoolUsageMetricsFakesYieldInjector injectsTheFakeData = new TestListPoolUsageMetricsFakesYieldInjector(pums);
// trigger the call and get our own data back to be tested
List<Microsoft.Azure.Batch.PoolUsageMetrics> clList = batchCli.PoolOperations.ListPoolUsageMetrics(additionalBehaviors: new[] { injectsTheFakeData }).ToList();
// test that our data are honored
for (int j = 0; j < 4; j++)
{
string id = "my fancy pool id " + j.ToString();
Assert.Equal(id, clList[j].PoolId);
Assert.Equal(endTime, clList[j].EndTime);
Assert.Equal(startTime, clList[j].StartTime);
Assert.Equal(totalCoreHours, clList[j].TotalCoreHours);
Assert.Equal(virtualMachineSize, clList[j].VirtualMachineSize);
}
List<PoolUsageMetrics> list = batchCli.PoolOperations.ListPoolUsageMetrics(DateTime.Now - TimeSpan.FromDays(1)).ToList();
}
};
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void TestPoolObjectResizeStopResize()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string poolId = "TestPoolObjectResizeStopResize" + TestUtilities.GetMyName();
const int targetDedicated = 0;
const int newTargetDedicated = 1;
try
{
//Create a pool
CloudPool pool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: targetDedicated);
pool.Commit();
TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromSeconds(20)).Wait();
this.testOutputHelper.WriteLine($"Created pool {poolId}");
CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId);
//Resize the pool
boundPool.Resize(newTargetDedicated, 0);
boundPool.Refresh();
Assert.Equal(AllocationState.Resizing, boundPool.AllocationState);
boundPool.StopResize();
boundPool.Refresh();
//The pool could be in stopping or steady state
this.testOutputHelper.WriteLine($"Pool allocation state: {boundPool.AllocationState}");
Assert.True(boundPool.AllocationState == AllocationState.Steady || boundPool.AllocationState == AllocationState.Stopping);
}
finally
{
//Delete the pool
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongDuration)]
public void TestPoolAutoscaleVerbs()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string poolId = TestUtilities.GenerateResourceId();
const int targetDedicated = 0;
const string autoscaleFormula1 = "$TargetDedicatedNodes=0;$TargetLowPriorityNodes=0;$NodeDeallocationOption=requeue";
const string autoscaleFormula2 = "$TargetDedicatedNodes=0;$TargetLowPriorityNodes=0;$NodeDeallocationOption=terminate";
const string evaluateAutoscaleFormula = "myActiveSamples=$ActiveTasks.GetSample(5);";
TimeSpan enableAutoScaleMinimumDelay = TimeSpan.FromSeconds(30); // compiler says can't be const
try
{
//Create a pool
CloudPool pool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicated);
pool.Commit();
TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromSeconds(20)).Wait();
CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId);
//Enable autoscale (via instance)
boundPool.EnableAutoScale(autoscaleFormula1);
DateTime utcEarliestCanCallEnableASAgain = DateTime.UtcNow + enableAutoScaleMinimumDelay;
boundPool.Refresh();
Assert.True(boundPool.AutoScaleEnabled);
Assert.Equal(autoscaleFormula1, boundPool.AutoScaleFormula);
this.testOutputHelper.WriteLine($"Got the pool");
Assert.NotNull(boundPool.AutoScaleRun);
Assert.NotNull(boundPool.AutoScaleRun.Results);
Assert.Contains(autoscaleFormula1, boundPool.AutoScaleRun.Results);
//Evaluate a different formula
AutoScaleRun evaluation = boundPool.EvaluateAutoScale(evaluateAutoscaleFormula);
this.testOutputHelper.WriteLine("Autoscale evaluate results: {0}", evaluation.Results);
Assert.NotNull(evaluation.Results);
Assert.Contains("myActiveSamples", evaluation.Results);
//Disable autoscale (via instance)
boundPool.DisableAutoScale();
boundPool.Refresh();
Assert.False(boundPool.AutoScaleEnabled);
//Wait for the pool to go to steady state
TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(2)).Wait();
// about to call EnableAutoScale again, must delay to avoid throttle exception
if (DateTime.UtcNow < utcEarliestCanCallEnableASAgain)
{
TimeSpan delayBeforeNextEnableASCall = utcEarliestCanCallEnableASAgain - DateTime.UtcNow;
Thread.Sleep(delayBeforeNextEnableASCall);
}
//Enable autoscale (via operations)
batchCli.PoolOperations.EnableAutoScale(poolId, autoscaleFormula2);
boundPool.Refresh();
Assert.True(boundPool.AutoScaleEnabled);
Assert.Equal(autoscaleFormula2, boundPool.AutoScaleFormula);
Assert.NotNull(boundPool.AutoScaleRun);
Assert.NotNull(boundPool.AutoScaleRun.Results);
Assert.Contains(autoscaleFormula2, boundPool.AutoScaleRun.Results);
evaluation = batchCli.PoolOperations.EvaluateAutoScale(poolId, evaluateAutoscaleFormula);
this.testOutputHelper.WriteLine("Autoscale evaluate results: {0}", evaluation.Results);
Assert.NotNull(evaluation);
Assert.Contains("myActiveSamples", evaluation.Results);
batchCli.PoolOperations.DisableAutoScale(poolId);
boundPool.Refresh();
Assert.False(boundPool.AutoScaleEnabled);
}
finally
{
//Delete the pool
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, LongTestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public async Task TestServerRejectsNonExistantVNetWithCorrectError()
{
Func<Task> test = async () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string poolId = "TestPoolVNet" + TestUtilities.GetMyName();
const int targetDedicated = 0;
string dummySubnetId = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.ClassicNetwork/virtualNetworks/vnet1/subnets/subnet1",
TestCommon.Configuration.BatchSubscription,
TestCommon.Configuration.BatchAccountResourceGroup);
try
{
CloudPool pool = batchCli.PoolOperations.CreatePool(
poolId,
PoolFixture.VMSize,
new CloudServiceConfiguration(PoolFixture.OSFamily),
targetDedicated);
pool.NetworkConfiguration = new NetworkConfiguration()
{
SubnetId = dummySubnetId
};
BatchException exception = await TestUtilities.AssertThrowsAsync<BatchException>(async () => await pool.CommitAsync().ConfigureAwait(false)).ConfigureAwait(false);
Assert.Equal(BatchErrorCodeStrings.InvalidPropertyValue, exception.RequestInformation.BatchError.Code);
Assert.Equal("Either the specified VNet does not exist, or the Batch service does not have access to it", exception.RequestInformation.BatchError.Values.Single(value => value.Key == "Reason").Value);
}
finally
{
//Delete the pool
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
}
};
await SynchronizationContextHelper.RunTestAsync(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void TestPoolCreatedWithUserAccountsSucceeds()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result)
{
string poolId = "TestPoolCreatedWithUserAccounts" + TestUtilities.GetMyName();
const int targetDedicated = 0;
try
{
var nodeUserPassword = TestUtilities.GenerateRandomPassword();
//Create a pool
CloudPool pool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicated);
pool.UserAccounts = new List<UserAccount>()
{
new UserAccount("test1", nodeUserPassword),
new UserAccount("test2", nodeUserPassword, ElevationLevel.NonAdmin),
new UserAccount("test3", nodeUserPassword, ElevationLevel.Admin),
new UserAccount("test4", nodeUserPassword, linuxUserConfiguration: new LinuxUserConfiguration(sshPrivateKey: "AAAA==")),
};
pool.Commit();
CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId);
Assert.Equal(pool.UserAccounts.Count, boundPool.UserAccounts.Count);
var results = pool.UserAccounts.Zip(boundPool.UserAccounts, (expected, actual) => new { Submitted = expected, Returned = actual });
foreach (var result in results)
{
Assert.Equal(result.Submitted.Name, result.Returned.Name);
Assert.Null(result.Returned.Password);
Assert.Equal(result.Submitted.ElevationLevel ?? ElevationLevel.NonAdmin, result.Returned.ElevationLevel);
Assert.Null(result.Returned.LinuxUserConfiguration?.SshPrivateKey);
}
}
finally
{
//Delete the pool
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, LongTestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void TestPoolCreatedOSDiskSucceeds()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result)
{
string poolId = nameof(TestPoolCreatedOSDiskSucceeds) + TestUtilities.GetMyName();
const int targetDedicated = 0;
try
{
var imageDetails = IaasLinuxPoolFixture.GetUbuntuImageDetails(batchCli);
//Create a pool
CloudPool pool = batchCli.PoolOperations.CreatePool(
poolId,
PoolFixture.VMSize,
new VirtualMachineConfiguration(
imageDetails.ImageReference,
imageDetails.NodeAgentSkuId)
{
LicenseType = "Windows_Server"
},
targetDedicated);
pool.Commit();
pool.Refresh();
Assert.Equal("Windows_Server", pool.VirtualMachineConfiguration.LicenseType);
}
finally
{
//Delete the pool
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, LongTestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void TestPoolCreatedDataDiskSucceeds()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result)
{
string poolId = nameof(TestPoolCreatedDataDiskSucceeds) + TestUtilities.GetMyName();
const int targetDedicated = 0;
try
{
var imageDetails = IaasLinuxPoolFixture.GetUbuntuImageDetails(batchCli);
const int lun = 50;
const int diskSizeGB = 50;
//Create a pool
CloudPool pool = batchCli.PoolOperations.CreatePool(
poolId,
PoolFixture.VMSize,
new VirtualMachineConfiguration(
imageDetails.ImageReference,
imageDetails.NodeAgentSkuId)
{
DataDisks = new List<DataDisk>
{
new DataDisk(lun, diskSizeGB)
}
},
targetDedicated);
pool.Commit();
pool.Refresh();
Assert.Equal(lun, pool.VirtualMachineConfiguration.DataDisks.Single().Lun);
Assert.Equal(diskSizeGB, pool.VirtualMachineConfiguration.DataDisks.Single().DiskSizeGB);
}
finally
{
//Delete the pool
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, LongTestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void TestPoolCreatedCustomImageExpectedError()
{
Action test = () =>
{
Func<Task<string>> tokenProvider = () => IntegrationTestCommon.GetAuthenticationTokenAsync("https://batch.core.windows.net/");
using (var client = BatchClient.Open(new BatchTokenCredentials(TestCommon.Configuration.BatchAccountUrl, tokenProvider)))
{
string poolId = "TestPoolCreatedWithCustomImage" + TestUtilities.GetMyName();
const int targetDedicated = 0;
try
{
var imageDetails = IaasLinuxPoolFixture.GetUbuntuImageDetails(client);
//Create a pool
CloudPool pool = client.PoolOperations.CreatePool(
poolId,
PoolFixture.VMSize,
new VirtualMachineConfiguration(
new ImageReference(
$"/subscriptions/{TestCommon.Configuration.BatchSubscription}/resourceGroups/{TestCommon.Configuration.BatchAccountResourceGroup}/providers/Microsoft.Compute/galleries/FakeGallery/images/FakeImage/versions/FakeImageVersion"),
imageDetails.NodeAgentSkuId),
targetDedicated);
var exception = Assert.Throws<BatchException>(() => pool.Commit());
Assert.Equal("InsufficientPermissions", exception.RequestInformation.BatchError.Code);
Assert.Contains(
"The user identity used for this operation does not have the required privelege Microsoft.Compute/galleries/images/versions/read on the specified resource",
exception.RequestInformation.BatchError.Values.Single().Value);
}
finally
{
//Delete the pool
TestUtilities.DeletePoolIfExistsAsync(client, poolId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, LongTestTimeout);
}
[Theory]
[LiveTest]
[InlineData(1, 0)]
[InlineData(0, 1)]
[InlineData(1, null)]
[InlineData(null, 1)]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public async Task ResizePool_AcceptedByServer(int? targetDedicated, int? targetLowPriority)
{
Func<Task> test = async () =>
{
using (BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync().ConfigureAwait(false))
{
string poolId = TestUtilities.GenerateResourceId();
try
{
CloudPool pool = batchCli.PoolOperations.CreatePool(
poolId,
PoolFixture.VMSize,
new CloudServiceConfiguration(PoolFixture.OSFamily));
await pool.CommitAsync().ConfigureAwait(false);
await pool.RefreshAsync().ConfigureAwait(false);
await TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(1));
await pool.ResizeAsync(
targetDedicatedComputeNodes: targetDedicated,
targetLowPriorityComputeNodes: targetLowPriority,
resizeTimeout: TimeSpan.FromMinutes(10)).ConfigureAwait(false);
await pool.RefreshAsync().ConfigureAwait(false);
Assert.Equal(targetDedicated ?? 0, pool.TargetDedicatedComputeNodes);
Assert.Equal(targetLowPriority ?? 0, pool.TargetLowPriorityComputeNodes);
Assert.Equal(AllocationState.Resizing, pool.AllocationState);
}
finally
{
await TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).ConfigureAwait(false);
}
}
};
await SynchronizationContextHelper.RunTestAsync(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void PoolStateCount_IsReturnedFromServer()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result)
{
var nodeCounts = batchCli.PoolOperations.ListPoolNodeCounts();
Assert.NotEmpty(nodeCounts);
var poolId = nodeCounts.First().PoolId;
foreach (var poolNodeCount in nodeCounts)
{
Assert.NotEmpty(poolNodeCount.PoolId);
Assert.NotNull(poolNodeCount.Dedicated);
Assert.NotNull(poolNodeCount.LowPriority);
// Check a few properties at random
Assert.Equal(0, poolNodeCount.LowPriority.Unusable);
Assert.Equal(0, poolNodeCount.LowPriority.Offline);
}
var filteredNodeCounts = batchCli.PoolOperations.ListPoolNodeCounts(new ODATADetailLevel(filterClause: $"poolId eq '{poolId}'")).ToList();
Assert.Single(filteredNodeCounts);
}
};
SynchronizationContextHelper.RunTest(test, LongTestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)]
public void ListSupportedImages()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
var supportedImages = batchCli.PoolOperations.ListSupportedImages().ToList();
Assert.True(supportedImages.Count > 0);
foreach (ImageInformation imageInfo in supportedImages)
{
this.testOutputHelper.WriteLine("ImageInformation:");
this.testOutputHelper.WriteLine(" skuid: " + imageInfo.NodeAgentSkuId);
this.testOutputHelper.WriteLine(" OSType: " + imageInfo.OSType);
this.testOutputHelper.WriteLine(" publisher: " + imageInfo.ImageReference.Publisher);
this.testOutputHelper.WriteLine(" offer: " + imageInfo.ImageReference.Offer);
this.testOutputHelper.WriteLine(" sku: " + imageInfo.ImageReference.Sku);
this.testOutputHelper.WriteLine(" version: " + imageInfo.ImageReference.Version);
}
}
};
SynchronizationContextHelper.RunTest(test, timeout: TimeSpan.FromSeconds(60));
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public async Task CreatePool_WithBlobFuseMountConfiguration()
{
Func<Task> test = async () =>
{
using (BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync().ConfigureAwait(false))
{
string poolId = TestUtilities.GenerateResourceId();
const string containerName = "blobfusecontainer";
StagingStorageAccount storageAccount = TestUtilities.GetStorageCredentialsFromEnvironment();
CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(
new StorageCredentials(storageAccount.StorageAccount, storageAccount.StorageAccountKey),
blobEndpoint: storageAccount.BlobUri,
queueEndpoint: null,
tableEndpoint: null,
fileEndpoint: null);
CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference(containerName);
await container.CreateIfNotExistsAsync();
try
{
var imageDetails = IaasLinuxPoolFixture.GetUbuntuImageDetails(batchCli);
CloudPool pool = batchCli.PoolOperations.CreatePool(
poolId,
PoolFixture.VMSize,
new VirtualMachineConfiguration(
imageDetails.ImageReference,
imageDetails.NodeAgentSkuId));
pool.MountConfiguration = new List<MountConfiguration>
{
new MountConfiguration(
new AzureBlobFileSystemConfiguration(
storageAccount.StorageAccount,
containerName,
"foo",
AzureStorageAuthenticationKey.FromAccountKey(storageAccount.StorageAccountKey)))
};
await pool.CommitAsync().ConfigureAwait(false);
await pool.RefreshAsync().ConfigureAwait(false);
Assert.NotNull(pool.MountConfiguration);
Assert.NotEmpty(pool.MountConfiguration);
Assert.Equal(storageAccount.StorageAccount, pool.MountConfiguration.Single().AzureBlobFileSystemConfiguration.AccountName);
Assert.Equal(containerName, pool.MountConfiguration.Single().AzureBlobFileSystemConfiguration.ContainerName);
}
finally
{
await TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).ConfigureAwait(false);
}
}
};
await SynchronizationContextHelper.RunTestAsync(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void TestCreatePoolEncryptionEnabled()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result)
{
string poolId = nameof(TestCreatePoolEncryptionEnabled) + TestUtilities.GetMyName();
const int targetDedicated = 0;
try
{
var imageDetails = IaasLinuxPoolFixture.GetUbuntuImageDetails(batchCli);
//Create a pool
CloudPool pool = batchCli.PoolOperations.CreatePool(
poolId,
PoolFixture.VMSize,
new VirtualMachineConfiguration(
imageDetails.ImageReference,
imageDetails.NodeAgentSkuId)
{
DiskEncryptionConfiguration = new DiskEncryptionConfiguration(new List<DiskEncryptionTarget> { DiskEncryptionTarget.TemporaryDisk })
},
targetDedicated);
pool.Commit();
pool.Refresh();
Assert.Single(pool.VirtualMachineConfiguration.DiskEncryptionConfiguration.Targets, DiskEncryptionTarget.TemporaryDisk);
}
finally
{
//Delete the pool
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, LongTestTimeout);
}
#region Test helpers
/// <summary>
/// injects a fake response
/// </summary>
internal class TestListPoolUsageMetricsFakesYieldInjector : Protocol.RequestInterceptor
{
// the fake data to be returned
internal IList<Protocol.Models.PoolUsageMetrics> _poolUsageMetricsList;
// returns our response... the fake
private Task<AzureOperationResponse<IPage<Protocol.Models.PoolUsageMetrics>, Protocol.Models.PoolListUsageMetricsHeaders>> NewFunc(CancellationToken token)
{
var response = new AzureOperationResponse<IPage<Protocol.Models.PoolUsageMetrics>, Protocol.Models.PoolListUsageMetricsHeaders>()
{
Body = new FakePage<Protocol.Models.PoolUsageMetrics>(_poolUsageMetricsList)
};
return System.Threading.Tasks.Task.FromResult(response);
}
// replaces the func with our own func
private void RequestInterceptor(Protocol.IBatchRequest requestBase)
{
// mung the func
((PoolListPoolUsageMetricsBatchRequest)requestBase).ServiceRequestFunc = NewFunc;
}
private TestListPoolUsageMetricsFakesYieldInjector()
{
}
internal TestListPoolUsageMetricsFakesYieldInjector(IList<Protocol.Models.PoolUsageMetrics> poolUsageMetricsList)
{
// here is our interceptor
base.ModificationInterceptHandler = this.RequestInterceptor;
// remember our fake data
this._poolUsageMetricsList = poolUsageMetricsList;
}
}
private static void AddEnviornmentSettingsToStartTask(StartTask start, string envSettingName, string envSettingValue)
{
List<EnvironmentSetting> settings = new List<EnvironmentSetting>();
EnvironmentSetting newES = new EnvironmentSetting(envSettingName, envSettingValue);
settings.Add(newES);
start.EnvironmentSettings = settings;
foreach (EnvironmentSetting curES in start.EnvironmentSettings)
{
Assert.Equal(envSettingName, curES.Name);
Assert.Equal(envSettingValue, curES.Value);
}
}
private static void CheckEnvironmentSettingsOnStartTask(StartTask start, string envSettingName, string envSettingValue)
{
foreach (EnvironmentSetting curES in start.EnvironmentSettings)
{
Assert.Equal(envSettingName, curES.Name);
Assert.Equal(envSettingValue, curES.Value);
}
}
private static void MakeResourceFiles(StartTask start, string resourceFileSas, string resourceFileValue)
{
List<ResourceFile> files = new List<ResourceFile>();
ResourceFile newRR = ResourceFile.FromUrl(resourceFileSas, resourceFileValue);
files.Add(newRR);
start.ResourceFiles = files;
CheckResourceFiles(start, resourceFileSas, resourceFileValue);
}
/// <summary>
/// Asserts that the resource files in the StartTask exactly match
/// those created in MakeResourceFiles().
/// </summary>
/// <param name="st"></param>
private static void CheckResourceFiles(StartTask st, string resourceFileSas, string resourceFileValue)
{
foreach (ResourceFile curRF in st.ResourceFiles)
{
Assert.Equal(curRF.HttpUrl, resourceFileSas);
Assert.Equal(curRF.FilePath, resourceFileValue);
}
}
#endregion
}
/// <summary>
/// This class exists because XUnit doesn't run tests in a single class in parallel. To reduce test runtime,
/// the longest running pool tests have been split out into multiple classes.
/// </summary>
public class IntegrationCloudPoolLongRunningTests01
{
private readonly ITestOutputHelper testOutputHelper;
private static readonly TimeSpan LongTestTimeout = TimeSpan.FromMinutes(20);
public IntegrationCloudPoolLongRunningTests01(ITestOutputHelper testOutputHelper)
{
this.testOutputHelper = testOutputHelper;
//Note -- this class does not and should not need a pool fixture
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongLongDuration)]
public void LongRunning_RemovePoolComputeNodesResizeTimeout_ResizeErrorsPopulated()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string poolId = "Bug2251050_TestRemoveComputeNodesResizeTimeout_LR" + TestUtilities.GetMyName();
string jobId = "Bug2251050Job-" + TestUtilities.GetMyName();
const int targetDedicated = 2;
try
{
//Create a pool with 2 compute nodes
CloudPool pool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: targetDedicated);
pool.Commit();
this.testOutputHelper.WriteLine("Created pool {0}", poolId);
CloudPool refreshablePool = batchCli.PoolOperations.GetPool(poolId);
//Wait for compute node allocation
TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(5)).Wait();
refreshablePool.Refresh();
Assert.Equal(targetDedicated, refreshablePool.CurrentDedicatedComputeNodes);
IEnumerable<ComputeNode> computeNodes = refreshablePool.ListComputeNodes();
Assert.Equal(targetDedicated, computeNodes.Count());
//
//Create a job on this pool with targetDedicated tasks which run for 10m each
//
CloudJob workflowJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation() { PoolId = poolId });
workflowJob.Commit();
const int taskDurationSeconds = 600;
string taskCmdLine = string.Format("ping 127.0.0.1 -n {0}", taskDurationSeconds);
for (int i = 0; i < targetDedicated; i++)
{
string taskId = string.Format("T_{0}", i);
batchCli.JobOperations.AddTask(jobId, new CloudTask(taskId, taskCmdLine));
}
//
// Wait for tasks to both go to running
//
Utilities utilities = batchCli.Utilities;
TaskStateMonitor taskStateMonitor = utilities.CreateTaskStateMonitor();
taskStateMonitor.WaitAll(
batchCli.JobOperations.ListTasks(jobId),
Microsoft.Azure.Batch.Common.TaskState.Running,
TimeSpan.FromMinutes(20));
//
// Remove pool compute nodes
//
TimeSpan resizeTimeout = TimeSpan.FromMinutes(5);
batchCli.PoolOperations.RemoveFromPool(poolId, computeNodes, ComputeNodeDeallocationOption.TaskCompletion, resizeTimeout);
//
// Wait for the resize to timeout
//
TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(6)).Wait();
refreshablePool.Refresh();
Assert.NotNull(refreshablePool.ResizeErrors);
Assert.Equal(1, refreshablePool.ResizeErrors.Count);
var resizeError = refreshablePool.ResizeErrors.Single();
Assert.Equal(PoolResizeErrorCodes.AllocationTimedOut, resizeError.Code);
this.testOutputHelper.WriteLine("Resize error: {0}", resizeError.Message);
}
finally
{
//Delete the pool
TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait();
//Delete the job schedule
TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId).Wait();
}
}
};
SynchronizationContextHelper.RunTest(test, LongTestTimeout);
}
}
/// <summary>
/// This class exists because XUnit doesn't run tests in a single class in parallel. To reduce test runtime,
/// the longest running pool tests have been split out into multiple classes.
/// </summary>
public class IntegrationCloudPoolLongRunningTests02
{
private readonly ITestOutputHelper testOutputHelper;
private static readonly TimeSpan LongTestTimeout = TimeSpan.FromMinutes(20);
public IntegrationCloudPoolLongRunningTests02(ITestOutputHelper testOutputHelper)
{
this.testOutputHelper = testOutputHelper;
//Note -- this class does not and should not need a pool fixture
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongLongDuration)]
public void LongRunning_TestRemovePoolComputeNodes()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string poolId = "TestRemovePoolComputeNodes_LongRunning" + TestUtilities.GetMyName();
const int targetDedicated = 3;
try
{
//Create a pool
CloudPool pool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: targetDedicated);
pool.Commit();
this.testOutputHelper.WriteLine("Created pool {0}", poolId);
CloudPool refreshablePool = batchCli.PoolOperations.GetPool(poolId);
//Wait for compute node allocation
TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(10)).Wait();
refreshablePool.Refresh();
Assert.Equal(targetDedicated, refreshablePool.CurrentDedicatedComputeNodes);
IEnumerable<ComputeNode> computeNodes = refreshablePool.ListComputeNodes();
Assert.Equal(targetDedicated, computeNodes.Count());
//
//Remove first compute node from the pool
//
ComputeNode computeNodeToRemove = computeNodes.First();
//For Bug234298 ensure start task property doesn't throw
Assert.Null(computeNodeToRemove.StartTask);
this.testOutputHelper.WriteLine("Will remove compute node: {0}", computeNodeToRemove.Id);
//Remove the compute node from the pool by instance
refreshablePool.RemoveFromPool(computeNodeToRemove);
//Wait for pool to got to steady state again
TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(10)).Wait();
refreshablePool.Refresh();
//Ensure that the other ComputeNodes were not impacted and we now have 1 less ComputeNode
List<ComputeNode> computeNodesAfterRemove = refreshablePool.ListComputeNodes().ToList();
Assert.Equal(targetDedicated - 1, computeNodesAfterRemove.Count);
List<string> remainingComputeNodeIds = computeNodesAfterRemove.Select(computeNode => computeNode.Id).ToList();
foreach (ComputeNode originalComputeNode in computeNodes)
{
Assert.Contains(originalComputeNode.Id, remainingComputeNodeIds);
}
this.testOutputHelper.WriteLine("Verified that the compute node was removed correctly");
//
//Remove a second compute node from the pool
//
ComputeNode secondComputeNodeToRemove = computeNodesAfterRemove.First();
string secondComputeNodeToRemoveId = secondComputeNodeToRemove.Id;
//Remove the IComputeNode from the pool by id
refreshablePool.RemoveFromPool(secondComputeNodeToRemoveId);
//Wait for pool to got to steady state again
TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(10)).Wait();
refreshablePool.Refresh();
//Ensure that the other ComputeNodes were not impacted and we now have 1 less ComputeNode
computeNodesAfterRemove = refreshablePool.ListComputeNodes().ToList();
Assert.Single(computeNodesAfterRemove);
this.testOutputHelper.WriteLine("Verified that the compute node was removed correctly");
//
//Remove a 3rd compute node from pool
//
ComputeNode thirdComputeNodeToRemove = computeNodesAfterRemove.First();
string thirdComputeNodeToRemoveId = thirdComputeNodeToRemove.Id;
this.testOutputHelper.WriteLine("Will remove compute node: {0}", thirdComputeNodeToRemoveId);
//Remove the IComputeNode from the pool using the ComputeNode object
thirdComputeNodeToRemove.RemoveFromPool();
//Wait for pool to got to steady state again
TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(10)).Wait();
//Ensure that the other ComputeNodes were not impacted and we now have 1 less ComputeNode
computeNodesAfterRemove = refreshablePool.ListComputeNodes().ToList();
Assert.Empty(computeNodesAfterRemove);
this.testOutputHelper.WriteLine("Verified that the ComputeNode was removed correctly");
}
finally
{
//Delete the pool
batchCli.PoolOperations.DeletePool(poolId);
}
}
};
SynchronizationContextHelper.RunTest(test, LongTestTimeout);
}
}
/// <summary>
/// This class exists because XUnit doesn't run tests in a single class in parallel. To reduce test runtime,
/// the longest running pool tests have been split out into multiple classes.
/// </summary>
public class IntegrationCloudPoolLongRunningTests03
{
private readonly ITestOutputHelper testOutputHelper;
private static readonly TimeSpan LongTestTimeout = TimeSpan.FromMinutes(20);
public IntegrationCloudPoolLongRunningTests03(ITestOutputHelper testOutputHelper)
{
this.testOutputHelper = testOutputHelper;
//Note -- this class does not and should not need a pool fixture
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongLongDuration)]
public async Task LongRunning_LowPriorityComputeNodeAllocated_IsDedicatedFalse()
{
Func<Task> test = async () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string poolId = "TestLowPri_LongRunning" + TestUtilities.GetMyName();
const int targetLowPriority = 1;
try
{
//Create a pool
CloudPool pool = batchCli.PoolOperations.CreatePool(
poolId,
PoolFixture.VMSize,
new CloudServiceConfiguration(PoolFixture.OSFamily),
targetLowPriorityComputeNodes: targetLowPriority);
await pool.CommitAsync().ConfigureAwait(false);
this.testOutputHelper.WriteLine("Created pool {0}", poolId);
await pool.RefreshAsync().ConfigureAwait(false);
//Wait for compute node allocation
await TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(10)).ConfigureAwait(false);
//Refresh pool to get latest from server
await pool.RefreshAsync().ConfigureAwait(false);
Assert.Equal(targetLowPriority, pool.CurrentLowPriorityComputeNodes);
IEnumerable<ComputeNode> computeNodes = pool.ListComputeNodes();
Assert.Single(computeNodes);
ComputeNode node = computeNodes.Single();
Assert.False(node.IsDedicated);
}
finally
{
//Delete the pool
await TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).ConfigureAwait(false);
}
}
};
await SynchronizationContextHelper.RunTestAsync(test, LongTestTimeout);
}
}
[Collection("SharedPoolCollection")]
public class IntegrationCloudPoolTestsWithSharedPool
{
private readonly ITestOutputHelper testOutputHelper;
private readonly PoolFixture poolFixture;
private static readonly TimeSpan LongTestTimeout = TimeSpan.FromMinutes(20);
public IntegrationCloudPoolTestsWithSharedPool(ITestOutputHelper testOutputHelper, PaasWindowsPoolFixture poolFixture)
{
this.testOutputHelper = testOutputHelper;
this.poolFixture = poolFixture;
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongLongDuration)]
public void LongRunning_Bug1771277_1771278_RebootReimageComputeNode()
{
Action test = () =>
{
using (BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
{
string jobId = "LongRunning_Bug1771277_1771278_RebootReimageComputeNode" + TestUtilities.GetMyName();
try
{
//
// Get the pool and check its targets
//
CloudPool pool = batchCli.PoolOperations.GetPool(this.poolFixture.PoolId);
//
//Create a job on this pool with targetDedicated tasks which run for 2m each
//
const int taskDurationSeconds = 600;
CloudJob workflowJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation() { PoolId = this.poolFixture.PoolId });
workflowJob.Commit();
CloudJob boundWorkflowJob = batchCli.JobOperations.GetJob(jobId);
string taskCmdLine = string.Format("ping 127.0.0.1 -n {0}", taskDurationSeconds);
for (int i = 0; i < pool.CurrentDedicatedComputeNodes; i++)
{
string taskId = string.Format("T_{0}", i);
boundWorkflowJob.AddTask(new CloudTask(taskId, taskCmdLine));
}
//
// Wait for tasks to go to running
//
TaskStateMonitor taskStateMonitor = batchCli.Utilities.CreateTaskStateMonitor();
taskStateMonitor.WaitAll(
batchCli.JobOperations.ListTasks(jobId),
Microsoft.Azure.Batch.Common.TaskState.Running,
TimeSpan.FromMinutes(2));
//
// Reboot the compute nodes from the pool with requeue option and ensure tasks goes to Active again and compute node state goes to rebooting
//
IEnumerable<ComputeNode> computeNodes = pool.ListComputeNodes();
foreach (ComputeNode computeNode in computeNodes)
{
computeNode.Reboot(ComputeNodeRebootOption.Requeue);
}
//Ensure task goes to active state
taskStateMonitor = batchCli.Utilities.CreateTaskStateMonitor();
taskStateMonitor.WaitAll(
batchCli.JobOperations.ListTasks(jobId),
Microsoft.Azure.Batch.Common.TaskState.Active,
TimeSpan.FromMinutes(1));
//Ensure each compute node goes to rebooting state
IEnumerable<ComputeNode> rebootingComputeNodes = batchCli.PoolOperations.ListComputeNodes(this.poolFixture.PoolId);
foreach (ComputeNode computeNode in rebootingComputeNodes)
{
Assert.Equal(ComputeNodeState.Rebooting, computeNode.State);
}
//Wait for tasks to start to run again
taskStateMonitor = batchCli.Utilities.CreateTaskStateMonitor();
taskStateMonitor.WaitAll(
batchCli.JobOperations.ListTasks(jobId),
Microsoft.Azure.Batch.Common.TaskState.Running,
TimeSpan.FromMinutes(10));
//
// Reimage a compute node from the pool with terminate option and ensure task goes to completed and compute node state goes to reimaging
//
computeNodes = pool.ListComputeNodes();
foreach (ComputeNode computeNode in computeNodes)
{
computeNode.Reimage(ComputeNodeReimageOption.Terminate);
}
//Ensure task goes to completed state
taskStateMonitor = batchCli.Utilities.CreateTaskStateMonitor();
taskStateMonitor.WaitAll(
batchCli.JobOperations.ListTasks(jobId),
Microsoft.Azure.Batch.Common.TaskState.Completed,
TimeSpan.FromMinutes(1));
//Ensure each compute node goes to reimaging state
IEnumerable<ComputeNode> reimagingComputeNodes = batchCli.PoolOperations.ListComputeNodes(this.poolFixture.PoolId);
foreach (ComputeNode computeNode in reimagingComputeNodes)
{
Assert.Equal(ComputeNodeState.Reimaging, computeNode.State);
}
}
finally
{
//Delete the job
TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId).Wait();
//Wait until the compute nodes are idle again
//TODO: Use a Utilities waiter
TimeSpan computeNodeSteadyTimeout = TimeSpan.FromMinutes(15);
DateTime allocationWaitStartTime = DateTime.UtcNow;
DateTime timeoutAfterThisTimeUtc = allocationWaitStartTime.Add(computeNodeSteadyTimeout);
IEnumerable<ComputeNode> computeNodes = batchCli.PoolOperations.ListComputeNodes(this.poolFixture.PoolId);
while (computeNodes.Any(computeNode => computeNode.State != ComputeNodeState.Idle))
{
Thread.Sleep(TimeSpan.FromSeconds(10));
computeNodes = batchCli.PoolOperations.ListComputeNodes(this.poolFixture.PoolId).ToList();
Assert.False(DateTime.UtcNow > timeoutAfterThisTimeUtc, "Timed out waiting for compute nodes in pool to reach idle state");
}
}
}
};
SynchronizationContextHelper.RunTest(test, LongTestTimeout);
}
}
}
| |
// 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.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
{
internal partial class TodoCommentIncrementalAnalyzer : IIncrementalAnalyzer
{
public const string Name = "Todo Comment Document Worker";
private readonly TodoCommentIncrementalAnalyzerProvider _owner;
private readonly Workspace _workspace;
private readonly IOptionService _optionService;
private readonly TodoCommentTokens _todoCommentTokens;
private readonly TodoCommentState _state;
public TodoCommentIncrementalAnalyzer(Workspace workspace, IOptionService optionService, TodoCommentIncrementalAnalyzerProvider owner, TodoCommentTokens todoCommentTokens)
{
_workspace = workspace;
_optionService = optionService;
_owner = owner;
_todoCommentTokens = todoCommentTokens;
_state = new TodoCommentState();
}
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
// remove cache
_state.Remove(document.Id);
return _state.PersistAsync(document, new Data(VersionStamp.Default, VersionStamp.Default, ImmutableArray<TodoItem>.Empty), cancellationToken);
}
public async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(document.IsFromPrimaryBranch());
// it has an assumption that this will not be called concurrently for same document.
// in fact, in current design, it won't be even called concurrently for different documents.
// but, can be called concurrently for different documents in future if we choose to.
if (!_optionService.GetOption(InternalFeatureOnOffOptions.TodoComments))
{
return;
}
// use tree version so that things like compiler option changes are considered
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
var existingData = await _state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
if (existingData != null)
{
// check whether we can use the data as it is (can happen when re-using persisted data from previous VS session)
if (CheckVersions(document, textVersion, syntaxVersion, existingData))
{
Contract.Requires(_workspace == document.Project.Solution.Workspace);
RaiseTaskListUpdated(_workspace, document.Id, existingData.Items);
return;
}
}
var service = document.GetLanguageService<ITodoCommentService>();
if (service == null)
{
return;
}
var comments = await service.GetTodoCommentsAsync(document, _todoCommentTokens.GetTokens(_workspace), cancellationToken).ConfigureAwait(false);
var items = await CreateItemsAsync(document, comments, cancellationToken).ConfigureAwait(false);
var data = new Data(textVersion, syntaxVersion, items);
await _state.PersistAsync(document, data, cancellationToken).ConfigureAwait(false);
// * NOTE * cancellation can't throw after this point.
if (existingData == null || existingData.Items.Length > 0 || data.Items.Length > 0)
{
Contract.Requires(_workspace == document.Project.Solution.Workspace);
RaiseTaskListUpdated(_workspace, document.Id, data.Items);
}
}
private async Task<ImmutableArray<TodoItem>> CreateItemsAsync(Document document, IList<TodoComment> comments, CancellationToken cancellationToken)
{
var items = ImmutableArray.CreateBuilder<TodoItem>();
if (comments != null)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var syntaxTree = document.SupportsSyntaxTree ? await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false) : null;
foreach (var comment in comments)
{
items.Add(CreateItem(document, text, syntaxTree, comment));
}
}
return items.ToImmutable();
}
private TodoItem CreateItem(Document document, SourceText text, SyntaxTree tree, TodoComment comment)
{
var textSpan = new TextSpan(comment.Position, 0);
var location = tree == null ? Location.Create(document.FilePath, textSpan, text.Lines.GetLinePositionSpan(textSpan)) : tree.GetLocation(textSpan);
var originalLineInfo = location.GetLineSpan();
var mappedLineInfo = location.GetMappedLineSpan();
return new TodoItem(
comment.Descriptor.Priority,
comment.Message,
document.Project.Solution.Workspace,
document.Id,
mappedLine: mappedLineInfo.StartLinePosition.Line,
originalLine: originalLineInfo.StartLinePosition.Line,
mappedColumn: mappedLineInfo.StartLinePosition.Character,
originalColumn: originalLineInfo.StartLinePosition.Character,
mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(),
originalFilePath: document.FilePath);
}
public ImmutableArray<TodoItem> GetTodoItems(Workspace workspace, DocumentId id, CancellationToken cancellationToken)
{
var document = workspace.CurrentSolution.GetDocument(id);
if (document == null)
{
return ImmutableArray<TodoItem>.Empty;
}
// TODO let's think about what to do here. for now, let call it synchronously. also, there is no actual asynch-ness for the
// TryGetExistingDataAsync, API just happen to be async since our persistent API is async API. but both caller and implementor are
// actually not async.
var existingData = _state.TryGetExistingDataAsync(document, cancellationToken).WaitAndGetResult(cancellationToken);
if (existingData == null)
{
return ImmutableArray<TodoItem>.Empty;
}
return existingData.Items;
}
private static bool CheckVersions(Document document, VersionStamp textVersion, VersionStamp syntaxVersion, Data existingData)
{
// first check full version to see whether we can reuse data in same session, if we can't, check timestamp only version to see whether
// we can use it cross-session.
return document.CanReusePersistedTextVersion(textVersion, existingData.TextVersion) &&
document.CanReusePersistedSyntaxTreeVersion(syntaxVersion, existingData.SyntaxVersion);
}
internal ImmutableArray<TodoItem> GetItems_TestingOnly(DocumentId documentId)
{
return _state.GetItems_TestingOnly(documentId);
}
private void RaiseTaskListUpdated(Workspace workspace, DocumentId documentId, ImmutableArray<TodoItem> items)
{
if (_owner != null)
{
_owner.RaiseTaskListUpdated(documentId, workspace, documentId.ProjectId, documentId, items);
}
}
public void RemoveDocument(DocumentId documentId)
{
_state.Remove(documentId);
RaiseTaskListUpdated(_workspace, documentId, ImmutableArray<TodoItem>.Empty);
}
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e)
{
return e.Option == TodoCommentOptions.TokenList;
}
private class Data
{
public readonly VersionStamp TextVersion;
public readonly VersionStamp SyntaxVersion;
public readonly ImmutableArray<TodoItem> Items;
public Data(VersionStamp textVersion, VersionStamp syntaxVersion, ImmutableArray<TodoItem> items)
{
this.TextVersion = textVersion;
this.SyntaxVersion = syntaxVersion;
this.Items = items;
}
}
#region not used
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public void RemoveProject(ProjectId projectId)
{
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowGroupedWithinSpec.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.Linq;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.Util.Internal;
using Akka.Util.Internal.Collections;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
using static Akka.Streams.Tests.Dsl.TestConfig;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowGroupedWithinSpec : ScriptedTest
{
private ActorMaterializerSettings Settings { get; }
private ActorMaterializer Materializer { get; }
public FlowGroupedWithinSpec(ITestOutputHelper helper) : base(helper)
{
Settings = ActorMaterializerSettings.Create(Sys);
Materializer = ActorMaterializer.Create(Sys, Settings);
}
[Fact]
public void A_GroupedWithin_must_group_elements_within_the_duration()
{
this.AssertAllStagesStopped(() =>
{
var input = new Iterator<int>(Enumerable.Range(1, 10000));
var p = this.CreateManualPublisherProbe<int>();
var c = this.CreateManualSubscriberProbe<IEnumerable<int>>();
Source.FromPublisher(p)
.GroupedWithin(1000, TimeSpan.FromSeconds(1))
.To(Sink.FromSubscriber(c))
.Run(Materializer);
var pSub = p.ExpectSubscription();
var cSub = c.ExpectSubscription();
cSub.Request(100);
var demand1 = (int)pSub.ExpectRequest();
for (var i = 1; i <= demand1; i++)
pSub.SendNext(input.Next());
var demand2 = (int)pSub.ExpectRequest();
for (var i = 1; i <= demand2; i++)
pSub.SendNext(input.Next());
var demand3 = (int)pSub.ExpectRequest();
c.ExpectNext().ShouldAllBeEquivalentTo(Enumerable.Range(1, demand1 + demand2));
for (var i = 1; i <= demand3; i++)
pSub.SendNext(input.Next());
c.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
c.ExpectNext()
.ShouldAllBeEquivalentTo(Enumerable.Range(demand1 + demand2 + 1, demand3));
c.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
pSub.ExpectRequest();
var last = input.Next();
pSub.SendNext(last);
pSub.SendComplete();
c.ExpectNext().Should().HaveCount(1).And.HaveElementAt(0, last);
c.ExpectComplete();
c.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
}, Materializer);
}
[Fact]
public void A_GroupedWithin_must_deliver_buffered_elements_OnComplete_before_the_timeout()
{
var c = this.CreateManualSubscriberProbe<IEnumerable<int>>();
Source.From(Enumerable.Range(1, 3))
.GroupedWithin(1000, TimeSpan.FromSeconds(10))
.To(Sink.FromSubscriber(c))
.Run(Materializer);
var cSub = c.ExpectSubscription();
cSub.Request(100);
c.ExpectNext().ShouldAllBeEquivalentTo(new[] { 1, 2, 3 });
c.ExpectComplete();
c.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
}
[Fact]
public void A_GroupedWithin_must_buffer_groups_until_requested_from_downstream()
{
var input = new Iterator<int>(Enumerable.Range(1, 10000));
var p = this.CreateManualPublisherProbe<int>();
var c = this.CreateManualSubscriberProbe<IEnumerable<int>>();
Source.FromPublisher(p)
.GroupedWithin(1000, TimeSpan.FromSeconds(1))
.To(Sink.FromSubscriber(c))
.Run(Materializer);
var pSub = p.ExpectSubscription();
var cSub = c.ExpectSubscription();
cSub.Request(1);
var demand1 = (int)pSub.ExpectRequest();
for (var i = 1; i <= demand1; i++)
pSub.SendNext(input.Next());
c.ExpectNext().ShouldAllBeEquivalentTo(Enumerable.Range(1, demand1));
var demand2 = (int)pSub.ExpectRequest();
for (var i = 1; i <= demand2; i++)
pSub.SendNext(input.Next());
c.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
cSub.Request(1);
c.ExpectNext().ShouldAllBeEquivalentTo(Enumerable.Range(demand1 + 1, demand2));
pSub.SendComplete();
c.ExpectComplete();
c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}
[Fact]
public void A_GroupedWithin_must_drop_empty_groups()
{
var p = this.CreateManualPublisherProbe<int>();
var c = this.CreateManualSubscriberProbe<IEnumerable<int>>();
Source.FromPublisher(p)
.GroupedWithin(1000, TimeSpan.FromMilliseconds(500))
.To(Sink.FromSubscriber(c))
.Run(Materializer);
var pSub = p.ExpectSubscription();
var cSub = c.ExpectSubscription();
cSub.Request(2);
pSub.ExpectRequest();
c.ExpectNoMsg(TimeSpan.FromMilliseconds(600));
pSub.SendNext(1);
pSub.SendNext(2);
c.ExpectNext().ShouldAllBeEquivalentTo(new [] {1,2});
// nothing more requested
c.ExpectNoMsg(TimeSpan.FromMilliseconds(1100));
cSub.Request(3);
c.ExpectNoMsg(TimeSpan.FromMilliseconds(600));
pSub.SendComplete();
c.ExpectComplete();
c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}
[Fact]
public void A_GroupedWithin_must_not_emit_empty_group_when_finished_while_not_being_pushed()
{
var p = this.CreateManualPublisherProbe<int>();
var c = this.CreateManualSubscriberProbe<IEnumerable<int>>();
Source.FromPublisher(p)
.GroupedWithin(1000, TimeSpan.FromMilliseconds(50))
.To(Sink.FromSubscriber(c))
.Run(Materializer);
var pSub = p.ExpectSubscription();
var cSub = c.ExpectSubscription();
cSub.Request(1);
pSub.ExpectRequest();
pSub.SendComplete();
c.ExpectComplete();
}
[Fact]
public void A_GroupedWithin_must_reset_time_window_when_max_elements_reached()
{
var input = new Iterator<int>(Enumerable.Range(1, 10000));
var upstream = this.CreatePublisherProbe<int>();
var downstream = this.CreateSubscriberProbe<IEnumerable<int>>();
Source.FromPublisher(upstream)
.GroupedWithin(3, TimeSpan.FromSeconds(2))
.To(Sink.FromSubscriber(downstream))
.Run(Materializer);
downstream.Request(2);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(1000));
Enumerable.Range(1,4).ForEach(_=>upstream.SendNext(input.Next()));
downstream.Within(TimeSpan.FromMilliseconds(1000), () =>
{
downstream.ExpectNext().ShouldAllBeEquivalentTo(new[] {1, 2, 3});
return NotUsed.Instance;
});
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(1500));
downstream.Within(TimeSpan.FromMilliseconds(1000), () =>
{
downstream.ExpectNext().ShouldAllBeEquivalentTo(new[] {4});
return NotUsed.Instance;
});
upstream.SendComplete();
downstream.ExpectComplete();
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}
[Fact]
public void A_GroupedWithin_must_group_early()
{
var random = new Random();
var script = Script.Create(RandomTestRange(Sys).Select(_ =>
{
var x = random.Next();
var y = random.Next();
var z = random.Next();
return Tuple.Create<ICollection<int>, ICollection<IEnumerable<int>>>(new[] {x, y, z},
new[] {new[] {x, y, z}});
}).ToArray());
RandomTestRange(Sys)
.ForEach(_ => RunScript(script, Settings, flow => flow.GroupedWithin(3, TimeSpan.FromMinutes(10))));
}
[Fact]
public void A_GroupedWithin_must_group_with_rest()
{
var random = new Random();
Func<Script<int, IEnumerable<int>>> script = () =>
{
var i = random.Next();
var rest = Tuple.Create<ICollection<int>, ICollection<IEnumerable<int>>>(new[] {i}, new[] {new[] {i}});
return Script.Create(RandomTestRange(Sys).Select(_ =>
{
var x = random.Next();
var y = random.Next();
var z = random.Next();
return Tuple.Create<ICollection<int>, ICollection<IEnumerable<int>>>(new[] { x, y, z },
new[] { new[] { x, y, z }});
}).Concat(rest).ToArray());
};
RandomTestRange(Sys)
.ForEach(_ => RunScript(script(), Settings, flow => flow.GroupedWithin(3, TimeSpan.FromMinutes(10))));
}
[Fact]
public void A_GroupedWithin_must_group_with_small_groups_with_backpressure()
{
var t = Source.From(Enumerable.Range(1, 10))
.GroupedWithin(1, TimeSpan.FromDays(1))
.Throttle(1, TimeSpan.FromMilliseconds(110), 0, ThrottleMode.Shaping)
.RunWith(Sink.Seq<IEnumerable<int>>(), Materializer);
t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10).Select(i => new List<int> {i}));
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Web;
using umbraco.interfaces;
using umbraco.BusinessLogic.Utils;
using umbraco.BusinessLogic;
using umbraco.BasePages;
namespace umbraco.cms.presentation.Trees
{
/// <summary>
/// A collection of TreeDefinitions found in any loaded assembly.
/// </summary>
public class TreeDefinitionCollection : List<TreeDefinition>
{
//create singleton
private static readonly TreeDefinitionCollection instance = new TreeDefinitionCollection();
private static readonly ReaderWriterLockSlim Lock = new ReaderWriterLockSlim();
public static TreeDefinitionCollection Instance
{
get
{
instance.EnsureTreesRegistered();
return instance;
}
}
/// <summary>
/// Find the TreeDefinition object based on the ITree
/// </summary>
/// <param name="tree"></param>
/// <returns></returns>
public TreeDefinition FindTree(ITree tree)
{
EnsureTreesRegistered();
var foundTree = this.Find(
t => t.TreeType == tree.GetType()
);
if (foundTree != null)
return foundTree;
return null;
}
/// <summary>
/// Finds the TreeDefinition with the generic type specified
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public TreeDefinition FindTree<T>() where T : ITree
{
EnsureTreesRegistered();
var foundTree = this.Find(
delegate(TreeDefinition t)
{
// zb-00002 #29929 : use IsAssignableFrom instead of Equal, otherwise you can't override build-in
// trees because for ex. PermissionEditor.aspx.cs OnInit calls FindTree<loadContent>()
return typeof(T).IsAssignableFrom(t.TreeType);
}
);
if (foundTree != null)
return foundTree;
return null;
}
/// <summary>
/// Return the TreeDefinition object based on the tree alias and application it belongs to
/// </summary>
/// <param name="alias"></param>
/// <returns></returns>
public TreeDefinition FindTree(string alias)
{
EnsureTreesRegistered();
var foundTree = this.Find(
t => t.Tree.Alias.ToLower() == alias.ToLower()
);
if (foundTree != null)
return foundTree;
return null;
}
/// <summary>
/// Return a list of TreeDefinition's with the appAlias specified
/// </summary>
/// <param name="appAlias"></param>
/// <returns></returns>
public List<TreeDefinition> FindTrees(string appAlias)
{
EnsureTreesRegistered();
return this.FindAll(
tree => (tree.App != null && tree.App.alias.ToLower() == appAlias.ToLower())
);
}
/// <summary>
/// Return a list of TreeDefinition's with the appAlias specified
/// </summary>
/// <param name="appAlias"></param>
/// <returns></returns>
public List<TreeDefinition> FindActiveTrees(string appAlias)
{
EnsureTreesRegistered();
return this.FindAll(
tree => (tree.App != null && tree.App.alias.ToLower() == appAlias.ToLower() && tree.Tree.Initialize)
);
}
public void ReRegisterTrees()
{
EnsureTreesRegistered(true);
}
/// <summary>
/// Finds all instances of ITree in loaded assemblies, then finds their associated ApplicationTree and Application objects
/// and stores them together in a TreeDefinition class and adds the definition to our list.
/// This will also store an instance of each tree object in the TreeDefinition class which should be
/// used when referencing all tree classes.
/// </summary>
private void EnsureTreesRegistered(bool clearFirst = false)
{
using (var l = new UpgradeableReadLock(Lock))
{
if (clearFirst)
{
this.Clear();
}
//if we already have tree, exit
if (this.Count > 0)
return;
l.UpgradeToWriteLock();
var foundITrees = PluginManager.Current.ResolveTrees();
var objTrees = ApplicationTree.getAll();
var appTrees = new List<ApplicationTree>();
appTrees.AddRange(objTrees);
var apps = Application.getAll();
foreach (var type in foundITrees)
{
//find the Application tree's who's combination of assembly name and tree type is equal to
//the Type that was found's full name.
//Since a tree can exist in multiple applications we'll need to register them all.
//The logic of this has changed in 6.0: http://issues.umbraco.org/issue/U4-1360
// we will support the old legacy way but the normal way is to match on assembly qualified names
var appTreesForType = appTrees.FindAll(
tree =>
{
//match the type on assembly qualified name if the assembly attribute is empty or if the
// tree type contains a comma (meaning it is assembly qualified)
if (tree.AssemblyName.IsNullOrWhiteSpace() || tree.Type.Contains(","))
{
return tree.GetRuntimeType() == type;
}
//otherwise match using legacy match rules
return (string.Format("{0}.{1}", tree.AssemblyName, tree.Type).InvariantEquals(type.FullName));
}
);
foreach (var appTree in appTreesForType)
{
//find the Application object whos name is the same as our appTree ApplicationAlias
var app = apps.Find(
a => (a.alias == appTree.ApplicationAlias)
);
var def = new TreeDefinition(type, appTree, app);
this.Add(def);
}
}
//sort our trees with the sort order definition
this.Sort((t1, t2) => t1.Tree.SortOrder.CompareTo(t2.Tree.SortOrder));
}
}
}
}
| |
// 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.Runtime.InteropServices;
using osu.Framework.Development;
using osu.Framework.Graphics.Batches;
using osu.Framework.Graphics.Primitives;
using osuTK.Graphics.ES30;
using osu.Framework.Statistics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.OpenGL.Vertices;
using osu.Framework.Graphics.Textures;
using osu.Framework.Platform;
using osuTK;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.Graphics.OpenGL.Textures
{
internal class TextureGLSingle : TextureGL
{
public const int MAX_MIPMAP_LEVELS = 3;
private static readonly Action<TexturedVertex2D> default_quad_action = new QuadBatch<TexturedVertex2D>(100, 1000).AddAction;
private readonly Queue<ITextureUpload> uploadQueue = new Queue<ITextureUpload>();
private int internalWidth;
private int internalHeight;
private readonly All filteringMode;
private TextureWrapMode internalWrapMode;
/// <summary>
/// The total amount of times this <see cref="TextureGLAtlas"/> was bound.
/// </summary>
public ulong BindCount { get; private set; }
// ReSharper disable once InconsistentlySynchronizedField (no need to lock here. we don't really care if the value is stale).
public override bool Loaded => textureId > 0 || uploadQueue.Count > 0;
public TextureGLSingle(int width, int height, bool manualMipmaps = false, All filteringMode = All.Linear)
{
Width = width;
Height = height;
this.manualMipmaps = manualMipmaps;
this.filteringMode = filteringMode;
}
#region Disposal
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
while (tryGetNextUpload(out var upload))
upload.Dispose();
GLWrapper.ScheduleDisposal(unload);
}
/// <summary>
/// Removes texture from GL memory.
/// </summary>
private void unload()
{
int disposableId = textureId;
if (disposableId <= 0)
return;
GL.DeleteTextures(1, new[] { disposableId });
memoryLease?.Dispose();
textureId = 0;
}
#endregion
#region Memory Tracking
private List<long> levelMemoryUsage = new List<long>();
private NativeMemoryTracker.NativeMemoryLease memoryLease;
private void updateMemoryUsage(int level, long newUsage)
{
if (levelMemoryUsage == null)
levelMemoryUsage = new List<long>();
while (level >= levelMemoryUsage.Count)
levelMemoryUsage.Add(0);
levelMemoryUsage[level] = newUsage;
memoryLease?.Dispose();
memoryLease = NativeMemoryTracker.AddMemory(this, getMemoryUsage());
}
private long getMemoryUsage()
{
long usage = 0;
for (int i = 0; i < levelMemoryUsage.Count; i++)
usage += levelMemoryUsage[i];
return usage;
}
#endregion
private int height;
public override TextureGL Native => this;
public override int Height
{
get => height;
set => height = value;
}
private int width;
public override int Width
{
get => width;
set => width = value;
}
private int textureId;
public override int TextureId
{
get
{
if (!Available)
throw new ObjectDisposedException(ToString(), "Can not obtain ID of a disposed texture.");
if (textureId == 0)
throw new InvalidOperationException("Can not obtain ID of a texture before uploading it.");
return textureId;
}
}
private static void rotateVector(ref Vector2 toRotate, float sin, float cos)
{
float oldX = toRotate.X;
toRotate.X = toRotate.X * cos - toRotate.Y * sin;
toRotate.Y = oldX * sin + toRotate.Y * cos;
}
public override RectangleF GetTextureRect(RectangleF? textureRect)
{
RectangleF texRect = textureRect != null
? new RectangleF(textureRect.Value.X, textureRect.Value.Y, textureRect.Value.Width, textureRect.Value.Height)
: new RectangleF(0, 0, Width, Height);
texRect.X /= width;
texRect.Y /= height;
texRect.Width /= width;
texRect.Height /= height;
return texRect;
}
public const int VERTICES_PER_TRIANGLE = 4;
internal override void DrawTriangle(Triangle vertexTriangle, ColourInfo drawColour, RectangleF? textureRect = null, Action<TexturedVertex2D> vertexAction = null,
Vector2? inflationPercentage = null)
{
if (!Available)
throw new ObjectDisposedException(ToString(), "Can not draw a triangle with a disposed texture.");
RectangleF texRect = GetTextureRect(textureRect);
Vector2 inflationAmount = inflationPercentage.HasValue ? new Vector2(inflationPercentage.Value.X * texRect.Width, inflationPercentage.Value.Y * texRect.Height) : Vector2.Zero;
RectangleF inflatedTexRect = texRect.Inflate(inflationAmount);
if (vertexAction == null)
vertexAction = default_quad_action;
// We split the triangle into two, such that we can obtain smooth edges with our
// texture coordinate trick. We might want to revert this to drawing a single
// triangle in case we ever need proper texturing, or if the additional vertices
// end up becoming an overhead (unlikely).
SRGBColour topColour = (drawColour.TopLeft + drawColour.TopRight) / 2;
SRGBColour bottomColour = (drawColour.BottomLeft + drawColour.BottomRight) / 2;
vertexAction(new TexturedVertex2D
{
Position = vertexTriangle.P0,
TexturePosition = new Vector2((inflatedTexRect.Left + inflatedTexRect.Right) / 2, inflatedTexRect.Top),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = inflationAmount,
Colour = topColour.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = vertexTriangle.P1,
TexturePosition = new Vector2(inflatedTexRect.Left, inflatedTexRect.Bottom),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = inflationAmount,
Colour = drawColour.BottomLeft.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = (vertexTriangle.P1 + vertexTriangle.P2) / 2,
TexturePosition = new Vector2((inflatedTexRect.Left + inflatedTexRect.Right) / 2, inflatedTexRect.Bottom),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = inflationAmount,
Colour = bottomColour.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = vertexTriangle.P2,
TexturePosition = new Vector2(inflatedTexRect.Right, inflatedTexRect.Bottom),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = inflationAmount,
Colour = drawColour.BottomRight.Linear,
});
FrameStatistics.Add(StatisticsCounterType.Pixels, (long)vertexTriangle.Area);
}
public const int VERTICES_PER_QUAD = 4;
internal override void DrawQuad(Quad vertexQuad, ColourInfo drawColour, RectangleF? textureRect = null, Action<TexturedVertex2D> vertexAction = null, Vector2? inflationPercentage = null,
Vector2? blendRangeOverride = null)
{
if (!Available)
throw new ObjectDisposedException(ToString(), "Can not draw a quad with a disposed texture.");
RectangleF texRect = GetTextureRect(textureRect);
Vector2 inflationAmount = inflationPercentage.HasValue ? new Vector2(inflationPercentage.Value.X * texRect.Width, inflationPercentage.Value.Y * texRect.Height) : Vector2.Zero;
RectangleF inflatedTexRect = texRect.Inflate(inflationAmount);
Vector2 blendRange = blendRangeOverride ?? inflationAmount;
if (vertexAction == null)
vertexAction = default_quad_action;
vertexAction(new TexturedVertex2D
{
Position = vertexQuad.BottomLeft,
TexturePosition = new Vector2(inflatedTexRect.Left, inflatedTexRect.Bottom),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = blendRange,
Colour = drawColour.BottomLeft.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = vertexQuad.BottomRight,
TexturePosition = new Vector2(inflatedTexRect.Right, inflatedTexRect.Bottom),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = blendRange,
Colour = drawColour.BottomRight.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = vertexQuad.TopRight,
TexturePosition = new Vector2(inflatedTexRect.Right, inflatedTexRect.Top),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = blendRange,
Colour = drawColour.TopRight.Linear,
});
vertexAction(new TexturedVertex2D
{
Position = vertexQuad.TopLeft,
TexturePosition = new Vector2(inflatedTexRect.Left, inflatedTexRect.Top),
TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom),
BlendRange = blendRange,
Colour = drawColour.TopLeft.Linear,
});
FrameStatistics.Add(StatisticsCounterType.Pixels, (long)vertexQuad.Area);
}
private void updateWrapMode()
{
if (!Available)
throw new ObjectDisposedException(ToString(), "Can not update wrap mode of a disposed texture.");
internalWrapMode = WrapMode;
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)internalWrapMode);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)internalWrapMode);
}
public override void SetData(ITextureUpload upload)
{
if (!Available)
throw new ObjectDisposedException(ToString(), "Can not set data of a disposed texture.");
if (upload.Bounds.IsEmpty && upload.Data.Length > 0)
{
upload.Bounds = new RectangleI(0, 0, width, height);
if (width * height > upload.Data.Length)
throw new InvalidOperationException($"Size of texture upload ({width}x{height}) does not contain enough data ({upload.Data.Length} < {width * height})");
}
IsTransparent = false;
lock (uploadQueue)
{
bool requireUpload = uploadQueue.Count == 0;
uploadQueue.Enqueue(upload);
if (requireUpload && !BypassTextureUploadQueueing)
GLWrapper.EnqueueTextureUpload(this);
}
}
public override bool Bind(TextureUnit unit = TextureUnit.Texture0)
{
if (!Available)
throw new ObjectDisposedException(ToString(), "Can not bind a disposed texture.");
Upload();
if (textureId <= 0)
return false;
if (IsTransparent)
return false;
if (GLWrapper.BindTexture(this, unit))
BindCount++;
if (internalWrapMode != WrapMode)
updateWrapMode();
return true;
}
private bool manualMipmaps;
internal override unsafe bool Upload()
{
if (!Available)
return false;
// We should never run raw OGL calls on another thread than the main thread due to race conditions.
ThreadSafety.EnsureDrawThread();
bool didUpload = false;
while (tryGetNextUpload(out ITextureUpload upload))
{
using (upload)
{
fixed (Rgba32* ptr = upload.Data)
DoUpload(upload, (IntPtr)ptr);
didUpload = true;
}
}
if (didUpload && !manualMipmaps)
{
GL.Hint(HintTarget.GenerateMipmapHint, HintMode.Nicest);
GL.GenerateMipmap(TextureTarget.Texture2D);
}
return didUpload;
}
internal override void FlushUploads()
{
while (tryGetNextUpload(out var upload))
upload.Dispose();
}
private bool tryGetNextUpload(out ITextureUpload upload)
{
lock (uploadQueue)
{
if (uploadQueue.Count == 0)
{
upload = null;
return false;
}
upload = uploadQueue.Dequeue();
return true;
}
}
protected virtual void DoUpload(ITextureUpload upload, IntPtr dataPointer)
{
// Do we need to generate a new texture?
if (textureId <= 0 || internalWidth != width || internalHeight != height)
{
internalWidth = width;
internalHeight = height;
// We only need to generate a new texture if we don't have one already. Otherwise just re-use the current one.
if (textureId <= 0)
{
int[] textures = new int[1];
GL.GenTextures(1, textures);
textureId = textures[0];
GLWrapper.BindTexture(this);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter,
(int)(manualMipmaps ? filteringMode : filteringMode == All.Linear ? All.LinearMipmapLinear : All.Nearest));
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)filteringMode);
// 33085 is GL_TEXTURE_MAX_LEVEL, which is not available within TextureParameterName.
// It controls the amount of mipmap levels generated by GL.GenerateMipmap later on.
GL.TexParameter(TextureTarget.Texture2D, (TextureParameterName)33085, MAX_MIPMAP_LEVELS);
updateWrapMode();
}
else
GLWrapper.BindTexture(this);
if (width == upload.Bounds.Width && height == upload.Bounds.Height || dataPointer == IntPtr.Zero)
{
updateMemoryUsage(upload.Level, (long)width * height * 4);
GL.TexImage2D(TextureTarget2d.Texture2D, upload.Level, TextureComponentCount.Srgb8Alpha8, width, height, 0, upload.Format, PixelType.UnsignedByte, dataPointer);
}
else
{
initializeLevel(upload.Level, width, height);
GL.TexSubImage2D(TextureTarget2d.Texture2D, upload.Level, upload.Bounds.X, upload.Bounds.Y, upload.Bounds.Width, upload.Bounds.Height, upload.Format,
PixelType.UnsignedByte, dataPointer);
}
}
// Just update content of the current texture
else if (dataPointer != IntPtr.Zero)
{
GLWrapper.BindTexture(this);
if (!manualMipmaps && upload.Level > 0)
{
//allocate mipmap levels
int level = 1;
int d = 2;
while (width / d > 0)
{
initializeLevel(level, width / d, height / d);
level++;
d *= 2;
}
manualMipmaps = true;
}
int div = (int)Math.Pow(2, upload.Level);
GL.TexSubImage2D(TextureTarget2d.Texture2D, upload.Level, upload.Bounds.X / div, upload.Bounds.Y / div, upload.Bounds.Width / div, upload.Bounds.Height / div,
upload.Format, PixelType.UnsignedByte, dataPointer);
}
}
private unsafe void initializeLevel(int level, int width, int height)
{
using (var image = new Image<Rgba32>(width, height))
{
fixed (void* buffer = &MemoryMarshal.GetReference(image.GetPixelSpan()))
{
updateMemoryUsage(level, (long)width * height * 4);
GL.TexImage2D(TextureTarget2d.Texture2D, level, TextureComponentCount.Srgb8Alpha8, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, (IntPtr)buffer);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using CrystalDecisions.Shared;
namespace WebApplication2
{
/// <summary>
/// Summary description for Main.
/// </summary>
public partial class MainPersReps : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
protected System.Web.UI.WebControls.Button lblResME;
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
Load_Main();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
private void Load_Main()
{
lblOrg.Text=Session["OrgName"].ToString();
}
private void btnSupplies_Click (object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "OrgId";
discreteval.Value = Session["OrgId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "ProfileOrg.rpt";
rpts();
}
private void btnReports_Click(object sender, System.EventArgs e)
{
Response.Redirect (strURL + "frmReports.aspx?");
}
private void rpts()
{
Session["Caller2"]="frmReportsPers";
Response.Redirect (strURL + "frmReportGen.aspx?");
}
protected void btnPhoneTree_Click(object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "LicenseId";
discreteval.Value = Session["LicenseId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "rptPhoneTree.rpt";
rpts();
}
protected void btnEmergencyTeams_Click(object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "OrgId";
discreteval.Value = Session["OrgId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "EmergencyGroups.rpt";
rpts();
}
protected void btnEmergencyProcedures_Click(object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "OrgId";
discreteval.Value = Session["OrgId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
ParameterField paramField2 = new ParameterField();
ParameterDiscreteValue discreteval2 = new ParameterDiscreteValue();
paramField2.ParameterFieldName = "Test";
discreteval2.Value = Session["Caller1"];
paramField2.CurrentValues.Add (discreteval2);
paramFields.Add (paramField2);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "EmergencyProcedures.rpt";
rpts();
}
protected void btnExit_Click(object sender, System.EventArgs e)
{
Response.Redirect(strURL + "Caller1" + ".aspx?");
}
protected void btnEmergencyResources_Click(object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "OrgId";
discreteval.Value = Session["OrgId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "rptEmergencyResources.rpt";
rpts();
}
protected void btnEmergencyGroups_Click(object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "OrgId";
discreteval.Value = Session["OrgId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "EmergencyTeams.rpt";
rpts();
}
private void btnOwnResources_Click(object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "OrgId";
discreteval.Value = Session["OrgId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "rptOwnResources.rpt";
rpts();
}
protected void btnProcedureSteps_Click(object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "OrgId";
discreteval.Value = Session["OrgId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "rptProcedureSteps.rpt";
rpts();
}
protected void btnAssess_Click(object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "LicenseId";
discreteval.Value = Session["LicenseId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "rptAssessOrgs.rpt";
rpts();
}
protected void btnServInputs_Click(object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "LicenseId";
discreteval.Value = Session["LicenseId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "rptServInputs.rpt";
rpts();
}
protected void btnRisks_Click(object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "OrgId";
discreteval.Value = Session["OrgId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "rptRisk.rpt";
rpts();
}
protected void btnPrep_Click(object sender, System.EventArgs e)
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "OrgId";
discreteval.Value = Session["OrgId"];
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "rptPreparationList.rpt";
rpts();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
**
** Purpose: Domains represent an application within the runtime. Objects can
** not be shared between domains and each domain can be configured
** independently.
**
**
=============================================================================*/
namespace System
{
using System;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Policy;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Reflection.Emit;
using CultureInfo = System.Globalization.CultureInfo;
using System.IO;
using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm;
using System.Text;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
[Serializable]
internal delegate void AppDomainInitializer(string[] args);
internal class AppDomainInitializerInfo
{
internal class ItemInfo
{
public string TargetTypeAssembly;
public string TargetTypeName;
public string MethodName;
}
internal ItemInfo[] Info;
internal AppDomainInitializerInfo(AppDomainInitializer init)
{
Info = null;
if (init == null)
return;
List<ItemInfo> itemInfo = new List<ItemInfo>();
List<AppDomainInitializer> nestedDelegates = new List<AppDomainInitializer>();
nestedDelegates.Add(init);
int idx = 0;
while (nestedDelegates.Count > idx)
{
AppDomainInitializer curr = nestedDelegates[idx++];
Delegate[] list = curr.GetInvocationList();
for (int i = 0; i < list.Length; i++)
{
if (!list[i].Method.IsStatic)
{
if (list[i].Target == null)
continue;
AppDomainInitializer nested = list[i].Target as AppDomainInitializer;
if (nested != null)
nestedDelegates.Add(nested);
else
throw new ArgumentException(SR.Arg_MustBeStatic,
list[i].Method.ReflectedType.FullName + "::" + list[i].Method.Name);
}
else
{
ItemInfo info = new ItemInfo();
info.TargetTypeAssembly = list[i].Method.ReflectedType.Module.Assembly.FullName;
info.TargetTypeName = list[i].Method.ReflectedType.FullName;
info.MethodName = list[i].Method.Name;
itemInfo.Add(info);
}
}
}
Info = itemInfo.ToArray();
}
internal AppDomainInitializer Unwrap()
{
if (Info == null)
return null;
AppDomainInitializer retVal = null;
for (int i = 0; i < Info.Length; i++)
{
Assembly assembly = Assembly.Load(Info[i].TargetTypeAssembly);
AppDomainInitializer newVal = (AppDomainInitializer)Delegate.CreateDelegate(typeof(AppDomainInitializer),
assembly.GetType(Info[i].TargetTypeName),
Info[i].MethodName);
if (retVal == null)
retVal = newVal;
else
retVal += newVal;
}
return retVal;
}
}
internal sealed class AppDomain
{
// Domain security information
// These fields initialized from the other side only. (NOTE: order
// of these fields cannot be changed without changing the layout in
// the EE- AppDomainBaseObject in this case)
private AppDomainManager _domainManager;
private Dictionary<String, Object> _LocalStore;
private AppDomainSetup _FusionStore;
private Evidence _SecurityIdentity;
#pragma warning disable 169
private Object[] _Policies; // Called from the VM.
#pragma warning restore 169
public event AssemblyLoadEventHandler AssemblyLoad;
private ResolveEventHandler _TypeResolve;
public event ResolveEventHandler TypeResolve
{
add
{
lock (this)
{
_TypeResolve += value;
}
}
remove
{
lock (this)
{
_TypeResolve -= value;
}
}
}
private ResolveEventHandler _ResourceResolve;
public event ResolveEventHandler ResourceResolve
{
add
{
lock (this)
{
_ResourceResolve += value;
}
}
remove
{
lock (this)
{
_ResourceResolve -= value;
}
}
}
private ResolveEventHandler _AssemblyResolve;
public event ResolveEventHandler AssemblyResolve
{
add
{
lock (this)
{
_AssemblyResolve += value;
}
}
remove
{
lock (this)
{
_AssemblyResolve -= value;
}
}
}
private ApplicationTrust _applicationTrust;
private EventHandler _processExit;
private EventHandler _domainUnload;
private UnhandledExceptionEventHandler _unhandledException;
// The compat flags are set at domain creation time to indicate that the given breaking
// changes (named in the strings) should not be used in this domain. We only use the
// keys, the vhe values are ignored.
private Dictionary<String, object> _compatFlags;
// Delegate that will hold references to FirstChance exception notifications
private EventHandler<FirstChanceExceptionEventArgs> _firstChanceException;
private IntPtr _pDomain; // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM.
private bool _HasSetPolicy;
private bool _IsFastFullTrustDomain; // quick check to see if the AppDomain is fully trusted and homogenous
private bool _compatFlagsInitialized;
internal const String TargetFrameworkNameAppCompatSetting = "TargetFrameworkName";
#if FEATURE_APPX
private static APPX_FLAGS s_flags;
//
// Keep in async with vm\appdomainnative.cpp
//
[Flags]
private enum APPX_FLAGS
{
APPX_FLAGS_INITIALIZED = 0x01,
APPX_FLAGS_APPX_MODEL = 0x02,
APPX_FLAGS_APPX_DESIGN_MODE = 0x04,
APPX_FLAGS_APPX_MASK = APPX_FLAGS_APPX_MODEL |
APPX_FLAGS_APPX_DESIGN_MODE,
}
private static APPX_FLAGS Flags
{
get
{
if (s_flags == 0)
s_flags = nGetAppXFlags();
Debug.Assert(s_flags != 0);
return s_flags;
}
}
#endif // FEATURE_APPX
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DisableFusionUpdatesFromADManager(AppDomainHandle domain);
#if FEATURE_APPX
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I4)]
private static extern APPX_FLAGS nGetAppXFlags();
#endif
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetAppDomainManagerType(AppDomainHandle domain,
StringHandleOnStack retAssembly,
StringHandleOnStack retType);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void SetAppDomainManagerType(AppDomainHandle domain,
string assembly,
string type);
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void SetSecurityHomogeneousFlag(AppDomainHandle domain,
[MarshalAs(UnmanagedType.Bool)] bool runtimeSuppliedHomogenousGrantSet);
/// <summary>
/// Get a handle used to make a call into the VM pointing to this domain
/// </summary>
internal AppDomainHandle GetNativeHandle()
{
// This should never happen under normal circumstances. However, there ar ways to create an
// uninitialized object through remoting, etc.
if (_pDomain.IsNull())
{
throw new InvalidOperationException(SR.Argument_InvalidHandle);
}
return new AppDomainHandle(_pDomain);
}
/// <summary>
/// If this AppDomain is configured to have an AppDomain manager then create the instance of it.
/// This method is also called from the VM to create the domain manager in the default domain.
/// </summary>
private void CreateAppDomainManager()
{
Debug.Assert(_domainManager == null, "_domainManager == null");
AppDomainSetup adSetup = FusionStore;
String trustedPlatformAssemblies = (String)(GetData("TRUSTED_PLATFORM_ASSEMBLIES"));
if (trustedPlatformAssemblies != null)
{
String platformResourceRoots = (String)(GetData("PLATFORM_RESOURCE_ROOTS"));
if (platformResourceRoots == null)
{
platformResourceRoots = String.Empty;
}
String appPaths = (String)(GetData("APP_PATHS"));
if (appPaths == null)
{
appPaths = String.Empty;
}
String appNiPaths = (String)(GetData("APP_NI_PATHS"));
if (appNiPaths == null)
{
appNiPaths = String.Empty;
}
String appLocalWinMD = (String)(GetData("APP_LOCAL_WINMETADATA"));
if (appLocalWinMD == null)
{
appLocalWinMD = String.Empty;
}
SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths, appLocalWinMD);
}
string domainManagerAssembly;
string domainManagerType;
GetAppDomainManagerType(out domainManagerAssembly, out domainManagerType);
if (domainManagerAssembly != null && domainManagerType != null)
{
try
{
_domainManager = CreateInstanceAndUnwrap(domainManagerAssembly, domainManagerType) as AppDomainManager;
}
catch (FileNotFoundException e)
{
throw new TypeLoadException(SR.Argument_NoDomainManager, e);
}
catch (SecurityException e)
{
throw new TypeLoadException(SR.Argument_NoDomainManager, e);
}
catch (TypeLoadException e)
{
throw new TypeLoadException(SR.Argument_NoDomainManager, e);
}
if (_domainManager == null)
{
throw new TypeLoadException(SR.Argument_NoDomainManager);
}
// If this domain was not created by a managed call to CreateDomain, then the AppDomainSetup
// will not have the correct values for the AppDomainManager set.
FusionStore.AppDomainManagerAssembly = domainManagerAssembly;
FusionStore.AppDomainManagerType = domainManagerType;
bool notifyFusion = _domainManager.GetType() != typeof(System.AppDomainManager) && !DisableFusionUpdatesFromADManager();
AppDomainSetup FusionStoreOld = null;
if (notifyFusion)
FusionStoreOld = new AppDomainSetup(FusionStore, true);
// Initialize the AppDomainMAnager and register the instance with the native host if requested
_domainManager.InitializeNewDomain(FusionStore);
if (notifyFusion)
SetupFusionStore(_FusionStore, FusionStoreOld); // Notify Fusion about the changes the user implementation of InitializeNewDomain may have made to the FusionStore object.
}
InitializeCompatibilityFlags();
}
/// <summary>
/// Initialize the compatibility flags to non-NULL values.
/// This method is also called from the VM when the default domain dosen't have a domain manager.
/// </summary>
private void InitializeCompatibilityFlags()
{
AppDomainSetup adSetup = FusionStore;
// set up shim flags regardless of whether we create a DomainManager in this method.
if (adSetup.GetCompatibilityFlags() != null)
{
_compatFlags = new Dictionary<String, object>(adSetup.GetCompatibilityFlags(), StringComparer.OrdinalIgnoreCase);
}
// for perf, we don't intialize the _compatFlags dictionary when we don't need to. However, we do need to make a
// note that we've run this method, because IsCompatibilityFlagsSet needs to return different values for the
// case where the compat flags have been setup.
Debug.Assert(!_compatFlagsInitialized);
_compatFlagsInitialized = true;
CompatibilitySwitches.InitializeSwitches();
}
/// <summary>
/// Returns the setting of the corresponding compatibility config switch (see CreateAppDomainManager for the impact).
/// </summary>
internal bool DisableFusionUpdatesFromADManager()
{
return DisableFusionUpdatesFromADManager(GetNativeHandle());
}
/// <summary>
/// Returns whether the current AppDomain follows the AppX rules.
/// </summary>
[Pure]
internal static bool IsAppXModel()
{
#if FEATURE_APPX
return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_MODEL) != 0;
#else
return false;
#endif
}
/// <summary>
/// Returns the setting of the AppXDevMode config switch.
/// </summary>
[Pure]
internal static bool IsAppXDesignMode()
{
#if FEATURE_APPX
return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_MASK) == (APPX_FLAGS.APPX_FLAGS_APPX_MODEL | APPX_FLAGS.APPX_FLAGS_APPX_DESIGN_MODE);
#else
return false;
#endif
}
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.LoadFrom.
/// </summary>
[Pure]
internal static void CheckLoadFromSupported()
{
#if FEATURE_APPX
if (IsAppXModel())
throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.LoadFrom"));
#endif
}
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.LoadFile.
/// </summary>
[Pure]
internal static void CheckLoadFileSupported()
{
#if FEATURE_APPX
if (IsAppXModel())
throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.LoadFile"));
#endif
}
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.ReflectionOnlyLoad.
/// </summary>
[Pure]
internal static void CheckReflectionOnlyLoadSupported()
{
#if FEATURE_APPX
if (IsAppXModel())
throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.ReflectionOnlyLoad"));
#endif
}
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.Load(byte[] ...).
/// </summary>
[Pure]
internal static void CheckLoadByteArraySupported()
{
#if FEATURE_APPX
if (IsAppXModel())
throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.Load(byte[], ...)"));
#endif
}
/// <summary>
/// Get the name of the assembly and type that act as the AppDomainManager for this domain
/// </summary>
internal void GetAppDomainManagerType(out string assembly, out string type)
{
// We can't just use our parameters because we need to ensure that the strings used for hte QCall
// are on the stack.
string localAssembly = null;
string localType = null;
GetAppDomainManagerType(GetNativeHandle(),
JitHelpers.GetStringHandleOnStack(ref localAssembly),
JitHelpers.GetStringHandleOnStack(ref localType));
assembly = localAssembly;
type = localType;
}
/// <summary>
/// Set the assembly and type which act as the AppDomainManager for this domain
/// </summary>
private void SetAppDomainManagerType(string assembly, string type)
{
Debug.Assert(assembly != null, "assembly != null");
Debug.Assert(type != null, "type != null");
SetAppDomainManagerType(GetNativeHandle(), assembly, type);
}
/// <summary>
/// Called for every AppDomain (including the default domain) to initialize the security of the AppDomain)
/// </summary>
private void InitializeDomainSecurity(Evidence providedSecurityInfo,
Evidence creatorsSecurityInfo,
bool generateDefaultEvidence,
IntPtr parentSecurityDescriptor,
bool publishAppDomain)
{
AppDomainSetup adSetup = FusionStore;
bool runtimeSuppliedHomogenousGrant = false;
ApplicationTrust appTrust = adSetup.ApplicationTrust;
if (appTrust != null)
{
SetupDomainSecurityForHomogeneousDomain(appTrust, runtimeSuppliedHomogenousGrant);
}
else if (_IsFastFullTrustDomain)
{
SetSecurityHomogeneousFlag(GetNativeHandle(), runtimeSuppliedHomogenousGrant);
}
// Get the evidence supplied for the domain. If no evidence was supplied, it means that we want
// to use the default evidence creation strategy for this domain
Evidence newAppDomainEvidence = (providedSecurityInfo != null ? providedSecurityInfo : creatorsSecurityInfo);
if (newAppDomainEvidence == null && generateDefaultEvidence)
{
newAppDomainEvidence = new Evidence();
}
// Set the evidence on the managed side
_SecurityIdentity = newAppDomainEvidence;
// Set the evidence of the AppDomain in the VM.
// Also, now that the initialization is complete, signal that to the security system.
// Finish the AppDomain initialization and resolve the policy for the AppDomain evidence.
SetupDomainSecurity(newAppDomainEvidence,
parentSecurityDescriptor,
publishAppDomain);
}
private void SetupDomainSecurityForHomogeneousDomain(ApplicationTrust appTrust,
bool runtimeSuppliedHomogenousGrantSet)
{
// If the CLR has supplied the homogenous grant set (that is, this domain would have been
// heterogenous in v2.0), then we need to strip the ApplicationTrust from the AppDomainSetup of
// the current domain. This prevents code which does:
// AppDomain.CreateDomain(..., AppDomain.CurrentDomain.SetupInformation);
//
// From looking like it is trying to create a homogenous domain intentionally, and therefore
// having its evidence check bypassed.
if (runtimeSuppliedHomogenousGrantSet)
{
BCLDebug.Assert(_FusionStore.ApplicationTrust != null, "Expected to find runtime supplied ApplicationTrust");
}
_applicationTrust = appTrust;
// Set the homogeneous bit in the VM's ApplicationSecurityDescriptor.
SetSecurityHomogeneousFlag(GetNativeHandle(),
runtimeSuppliedHomogenousGrantSet);
}
public AppDomainManager DomainManager
{
get
{
return _domainManager;
}
}
public ObjectHandle CreateInstance(String assemblyName,
String typeName)
{
// jit does not check for that, so we should do it ...
if (this == null)
throw new NullReferenceException();
if (assemblyName == null)
throw new ArgumentNullException(nameof(assemblyName));
Contract.EndContractBlock();
return Activator.CreateInstance(assemblyName,
typeName);
}
public static AppDomain CurrentDomain
{
get
{
Contract.Ensures(Contract.Result<AppDomain>() != null);
return Thread.GetDomain();
}
}
public String BaseDirectory
{
get
{
return FusionStore.ApplicationBase;
}
}
public override String ToString()
{
StringBuilder sb = StringBuilderCache.Acquire();
String fn = nGetFriendlyName();
if (fn != null)
{
sb.Append(SR.Loader_Name + fn);
sb.Append(Environment.NewLine);
}
if (_Policies == null || _Policies.Length == 0)
sb.Append(SR.Loader_NoContextPolicies
+ Environment.NewLine);
else
{
sb.Append(SR.Loader_ContextPolicies
+ Environment.NewLine);
for (int i = 0; i < _Policies.Length; i++)
{
sb.Append(_Policies[i]);
sb.Append(Environment.NewLine);
}
}
return StringBuilderCache.GetStringAndRelease(sb);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private extern Assembly[] nGetAssemblies(bool forIntrospection);
internal Assembly[] GetAssemblies(bool forIntrospection)
{
return nGetAssemblies(forIntrospection);
}
// this is true when we've removed the handles etc so really can't do anything
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsUnloadingForcedFinalize();
// this is true when we've just started going through the finalizers and are forcing objects to finalize
// so must be aware that certain infrastructure may have gone away
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern bool IsFinalizingForUnload();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void PublishAnonymouslyHostedDynamicMethodsAssembly(RuntimeAssembly assemblyHandle);
public void SetData(string name, object data)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
// SetData should only be used to set values that don't already exist.
object currentVal;
lock (((ICollection)LocalStore).SyncRoot)
{
LocalStore.TryGetValue(name, out currentVal);
}
if (currentVal != null)
{
throw new InvalidOperationException(SR.InvalidOperation_SetData_OnlyOnce);
}
lock (((ICollection)LocalStore).SyncRoot)
{
LocalStore[name] = data;
}
}
[Pure]
public Object GetData(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
int key = AppDomainSetup.Locate(name);
if (key == -1)
{
if (name.Equals(AppDomainSetup.LoaderOptimizationKey))
return FusionStore.LoaderOptimization;
else
{
object data;
lock (((ICollection)LocalStore).SyncRoot)
{
LocalStore.TryGetValue(name, out data);
}
if (data == null)
return null;
return data;
}
}
else
{
// Be sure to call these properties, not Value, so
// that the appropriate permission demand will be done
switch (key)
{
case (int)AppDomainSetup.LoaderInformation.ApplicationBaseValue:
return FusionStore.ApplicationBase;
case (int)AppDomainSetup.LoaderInformation.ApplicationNameValue:
return FusionStore.ApplicationName;
default:
Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
return null;
}
}
}
[Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[DllImport(Microsoft.Win32.Win32Native.KERNEL32)]
public static extern int GetCurrentThreadId();
private AppDomain()
{
throw new NotSupportedException(SR.GetResourceString(ResId.NotSupported_Constructor));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void nCreateContext();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nSetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD);
internal void SetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD)
{
nSetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPath, appNiPaths, appLocalWinMD);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern String nGetFriendlyName();
// support reliability for certain event handlers, if the target
// methods also participate in this discipline. If caller passes
// an existing MulticastDelegate, then we could use a MDA to indicate
// that reliability is not guaranteed. But if it is a single cast
// scenario, we can make it work.
public event EventHandler ProcessExit
{
add
{
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
lock (this)
_processExit += value;
}
}
remove
{
lock (this)
_processExit -= value;
}
}
public event EventHandler DomainUnload
{
add
{
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
lock (this)
_domainUnload += value;
}
}
remove
{
lock (this)
_domainUnload -= value;
}
}
public event UnhandledExceptionEventHandler UnhandledException
{
add
{
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
lock (this)
_unhandledException += value;
}
}
remove
{
lock (this)
_unhandledException -= value;
}
}
// This is the event managed code can wireup against to be notified
// about first chance exceptions.
//
// To register/unregister the callback, the code must be SecurityCritical.
public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException
{
add
{
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
lock (this)
_firstChanceException += value;
}
}
remove
{
lock (this)
_firstChanceException -= value;
}
}
private void OnAssemblyLoadEvent(RuntimeAssembly LoadedAssembly)
{
AssemblyLoadEventHandler eventHandler = AssemblyLoad;
if (eventHandler != null)
{
AssemblyLoadEventArgs ea = new AssemblyLoadEventArgs(LoadedAssembly);
eventHandler(this, ea);
}
}
// This method is called by the VM.
private RuntimeAssembly OnResourceResolveEvent(RuntimeAssembly assembly, String resourceName)
{
ResolveEventHandler eventHandler = _ResourceResolve;
if (eventHandler == null)
return null;
Delegate[] ds = eventHandler.GetInvocationList();
int len = ds.Length;
for (int i = 0; i < len; i++)
{
Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(resourceName, assembly));
RuntimeAssembly ret = GetRuntimeAssembly(asm);
if (ret != null)
return ret;
}
return null;
}
// This method is called by the VM
private RuntimeAssembly OnTypeResolveEvent(RuntimeAssembly assembly, String typeName)
{
ResolveEventHandler eventHandler = _TypeResolve;
if (eventHandler == null)
return null;
Delegate[] ds = eventHandler.GetInvocationList();
int len = ds.Length;
for (int i = 0; i < len; i++)
{
Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(typeName, assembly));
RuntimeAssembly ret = GetRuntimeAssembly(asm);
if (ret != null)
return ret;
}
return null;
}
// This method is called by the VM.
private RuntimeAssembly OnAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName)
{
ResolveEventHandler eventHandler = _AssemblyResolve;
if (eventHandler == null)
{
return null;
}
Delegate[] ds = eventHandler.GetInvocationList();
int len = ds.Length;
for (int i = 0; i < len; i++)
{
Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(assemblyFullName, assembly));
RuntimeAssembly ret = GetRuntimeAssembly(asm);
if (ret != null)
return ret;
}
return null;
}
#if FEATURE_COMINTEROP
// Called by VM - code:CLRPrivTypeCacheWinRT::RaiseDesignerNamespaceResolveEvent
private string[] OnDesignerNamespaceResolveEvent(string namespaceName)
{
return System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.OnDesignerNamespaceResolveEvent(this, namespaceName);
}
#endif // FEATURE_COMINTEROP
internal AppDomainSetup FusionStore
{
get
{
Debug.Assert(_FusionStore != null,
"Fusion store has not been correctly setup in this domain");
return _FusionStore;
}
}
internal static RuntimeAssembly GetRuntimeAssembly(Assembly asm)
{
if (asm == null)
return null;
RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
if (rtAssembly != null)
return rtAssembly;
AssemblyBuilder ab = asm as AssemblyBuilder;
if (ab != null)
return ab.InternalAssembly;
return null;
}
private Dictionary<String, Object> LocalStore
{
get
{
if (_LocalStore != null)
return _LocalStore;
else
{
_LocalStore = new Dictionary<String, Object>();
return _LocalStore;
}
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nSetNativeDllSearchDirectories(string paths);
private void SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo)
{
Contract.Requires(info != null);
if (info.ApplicationBase == null)
{
info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized: true);
}
nCreateContext();
if (info.LoaderOptimization != LoaderOptimization.NotSpecified || (oldInfo != null && info.LoaderOptimization != oldInfo.LoaderOptimization))
UpdateLoaderOptimization(info.LoaderOptimization);
// This must be the last action taken
_FusionStore = info;
}
private static void RunInitializer(AppDomainSetup setup)
{
if (setup.AppDomainInitializer != null)
{
string[] args = null;
if (setup.AppDomainInitializerArguments != null)
args = (string[])setup.AppDomainInitializerArguments.Clone();
setup.AppDomainInitializer(args);
}
}
// Used to switch into other AppDomain and call SetupRemoteDomain.
// We cannot simply call through the proxy, because if there
// are any remoting sinks registered, they can add non-mscorlib
// objects to the message (causing an assembly load exception when
// we try to deserialize it on the other side)
private static object PrepareDataForSetup(String friendlyName,
AppDomainSetup setup,
Evidence providedSecurityInfo,
Evidence creatorsSecurityInfo,
IntPtr parentSecurityDescriptor,
string sandboxName,
string[] propertyNames,
string[] propertyValues)
{
byte[] serializedEvidence = null;
bool generateDefaultEvidence = false;
AppDomainInitializerInfo initializerInfo = null;
if (setup != null && setup.AppDomainInitializer != null)
initializerInfo = new AppDomainInitializerInfo(setup.AppDomainInitializer);
// will travel x-Ad, drop non-agile data
AppDomainSetup newSetup = new AppDomainSetup(setup, false);
// Remove the special AppDomainCompatSwitch entries from the set of name value pairs
// And add them to the AppDomainSetup
//
// This is only supported on CoreCLR through ICLRRuntimeHost2.CreateAppDomainWithManager
// Desktop code should use System.AppDomain.CreateDomain() or
// System.AppDomainManager.CreateDomain() and add the flags to the AppDomainSetup
List<String> compatList = new List<String>();
if (propertyNames != null && propertyValues != null)
{
for (int i = 0; i < propertyNames.Length; i++)
{
if (String.Compare(propertyNames[i], "AppDomainCompatSwitch", StringComparison.OrdinalIgnoreCase) == 0)
{
compatList.Add(propertyValues[i]);
propertyNames[i] = null;
propertyValues[i] = null;
}
}
if (compatList.Count > 0)
{
newSetup.SetCompatibilitySwitches(compatList);
}
}
return new Object[]
{
friendlyName,
newSetup,
parentSecurityDescriptor,
generateDefaultEvidence,
serializedEvidence,
initializerInfo,
sandboxName,
propertyNames,
propertyValues
};
} // PrepareDataForSetup
private static Object Setup(Object arg)
{
Contract.Requires(arg != null && arg is Object[]);
Contract.Requires(((Object[])arg).Length >= 8);
Object[] args = (Object[])arg;
String friendlyName = (String)args[0];
AppDomainSetup setup = (AppDomainSetup)args[1];
IntPtr parentSecurityDescriptor = (IntPtr)args[2];
bool generateDefaultEvidence = (bool)args[3];
byte[] serializedEvidence = (byte[])args[4];
AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[5];
string sandboxName = (string)args[6];
string[] propertyNames = (string[])args[7]; // can contain null elements
string[] propertyValues = (string[])args[8]; // can contain null elements
// extract evidence
Evidence providedSecurityInfo = null;
Evidence creatorsSecurityInfo = null;
AppDomain ad = AppDomain.CurrentDomain;
AppDomainSetup newSetup = new AppDomainSetup(setup, false);
if (propertyNames != null && propertyValues != null)
{
for (int i = 0; i < propertyNames.Length; i++)
{
// We want to set native dll probing directories before any P/Invokes have a
// chance to fire. The Path class, for one, has P/Invokes.
if (propertyNames[i] == "NATIVE_DLL_SEARCH_DIRECTORIES")
{
if (propertyValues[i] == null)
throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
string paths = propertyValues[i];
if (paths.Length == 0)
break;
nSetNativeDllSearchDirectories(paths);
}
}
for (int i = 0; i < propertyNames.Length; i++)
{
if (propertyNames[i] == "APPBASE") // make sure in sync with Fusion
{
if (propertyValues[i] == null)
throw new ArgumentNullException("APPBASE");
if (PathInternal.IsPartiallyQualified(propertyValues[i]))
throw new ArgumentException(SR.Argument_AbsolutePathRequired);
newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
}
else if (propertyNames[i] == "LOADER_OPTIMIZATION")
{
if (propertyValues[i] == null)
throw new ArgumentNullException("LOADER_OPTIMIZATION");
switch (propertyValues[i])
{
case "SingleDomain": newSetup.LoaderOptimization = LoaderOptimization.SingleDomain; break;
case "MultiDomain": newSetup.LoaderOptimization = LoaderOptimization.MultiDomain; break;
case "MultiDomainHost": newSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost; break;
case "NotSpecified": newSetup.LoaderOptimization = LoaderOptimization.NotSpecified; break;
default: throw new ArgumentException(SR.Argument_UnrecognizedLoaderOptimization, "LOADER_OPTIMIZATION");
}
}
else if (propertyNames[i] == "TRUSTED_PLATFORM_ASSEMBLIES" ||
propertyNames[i] == "PLATFORM_RESOURCE_ROOTS" ||
propertyNames[i] == "APP_PATHS" ||
propertyNames[i] == "APP_NI_PATHS")
{
string values = propertyValues[i];
if (values == null)
throw new ArgumentNullException(propertyNames[i]);
ad.SetData(propertyNames[i], NormalizeAppPaths(values));
}
else if (propertyNames[i] != null)
{
ad.SetData(propertyNames[i], propertyValues[i]); // just propagate
}
}
}
ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup
// technically, we don't need this, newSetup refers to the same object as FusionStore
// but it's confusing since it isn't immediately obvious whether we have a ref or a copy
AppDomainSetup adSetup = ad.FusionStore;
adSetup.InternalSetApplicationTrust(sandboxName);
// set up the friendly name
ad.nSetupFriendlyName(friendlyName);
#if FEATURE_COMINTEROP
if (setup != null && setup.SandboxInterop)
{
ad.nSetDisableInterfaceCache();
}
#endif // FEATURE_COMINTEROP
// set up the AppDomainManager for this domain and initialize security.
if (adSetup.AppDomainManagerAssembly != null && adSetup.AppDomainManagerType != null)
{
ad.SetAppDomainManagerType(adSetup.AppDomainManagerAssembly, adSetup.AppDomainManagerType);
}
ad.CreateAppDomainManager(); // could modify FusionStore's object
ad.InitializeDomainSecurity(providedSecurityInfo,
creatorsSecurityInfo,
generateDefaultEvidence,
parentSecurityDescriptor,
true);
// can load user code now
if (initializerInfo != null)
adSetup.AppDomainInitializer = initializerInfo.Unwrap();
RunInitializer(adSetup);
return null;
}
private static string NormalizeAppPaths(string values)
{
int estimatedLength = values.Length + 1; // +1 for extra separator temporarily added at end
StringBuilder sb = StringBuilderCache.Acquire(estimatedLength);
for (int pos = 0; pos < values.Length; pos++)
{
string path;
int nextPos = values.IndexOf(Path.PathSeparator, pos);
if (nextPos == -1)
{
path = values.Substring(pos);
pos = values.Length - 1;
}
else
{
path = values.Substring(pos, nextPos - pos);
pos = nextPos;
}
// Skip empty directories
if (path.Length == 0)
continue;
if (PathInternal.IsPartiallyQualified(path))
throw new ArgumentException(SR.Argument_AbsolutePathRequired);
string appPath = NormalizePath(path, fullCheck: true);
sb.Append(appPath);
sb.Append(Path.PathSeparator);
}
// Strip the last separator
if (sb.Length > 0)
{
sb.Remove(sb.Length - 1, 1);
}
return StringBuilderCache.GetStringAndRelease(sb);
}
internal static string NormalizePath(string path, bool fullCheck)
{
return Path.GetFullPath(path);
}
// This routine is called from unmanaged code to
// set the default fusion context.
private void SetupDomain(bool allowRedirects, String path, String configFile, String[] propertyNames, String[] propertyValues)
{
// It is possible that we could have multiple threads initializing
// the default domain. We will just take the winner of these two.
// (eg. one thread doing a com call and another doing attach for IJW)
lock (this)
{
if (_FusionStore == null)
{
AppDomainSetup setup = new AppDomainSetup();
// always use internet permission set
setup.InternalSetApplicationTrust("Internet");
SetupFusionStore(setup, null);
}
}
}
private void SetupDomainSecurity(Evidence appDomainEvidence,
IntPtr creatorsSecurityDescriptor,
bool publishAppDomain)
{
Evidence stackEvidence = appDomainEvidence;
SetupDomainSecurity(GetNativeHandle(),
JitHelpers.GetObjectHandleOnStack(ref stackEvidence),
creatorsSecurityDescriptor,
publishAppDomain);
}
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void SetupDomainSecurity(AppDomainHandle appDomain,
ObjectHandleOnStack appDomainEvidence,
IntPtr creatorsSecurityDescriptor,
[MarshalAs(UnmanagedType.Bool)] bool publishAppDomain);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void nSetupFriendlyName(string friendlyName);
#if FEATURE_COMINTEROP
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void nSetDisableInterfaceCache();
#endif // FEATURE_COMINTEROP
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void UpdateLoaderOptimization(LoaderOptimization optimization);
public AppDomainSetup SetupInformation
{
get
{
return new AppDomainSetup(FusionStore, true);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern String IsStringInterned(String str);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern String GetOrInternString(String str);
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetGrantSet(AppDomainHandle domain, ObjectHandleOnStack retGrantSet);
public bool IsFullyTrusted
{
get
{
return true;
}
}
public Object CreateInstanceAndUnwrap(String assemblyName,
String typeName)
{
ObjectHandle oh = CreateInstance(assemblyName, typeName);
if (oh == null)
return null;
return oh.Unwrap();
} // CreateInstanceAndUnwrap
public Int32 Id
{
get
{
return GetId();
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern Int32 GetId();
}
/// <summary>
/// Handle used to marshal an AppDomain to the VM (eg QCall). When marshaled via a QCall, the target
/// method in the VM will recieve a QCall::AppDomainHandle parameter.
/// </summary>
internal struct AppDomainHandle
{
private IntPtr m_appDomainHandle;
// Note: generall an AppDomainHandle should not be directly constructed, instead the
// code:System.AppDomain.GetNativeHandle method should be called to get the handle for a specific
// AppDomain.
internal AppDomainHandle(IntPtr domainHandle)
{
m_appDomainHandle = domainHandle;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using Thrift.Collections;
using Thrift.Protocol;
using Thrift.Transport;
using Thrift.Test;
using System.Security.Authentication;
namespace Test
{
public class TestClient
{
private class TestParams
{
public int numIterations = 1;
public string host = "localhost";
public int port = 9090;
public string url;
public string pipe;
public bool buffered;
public bool framed;
public string protocol;
public bool encrypted = false;
protected bool _isFirstTransport = true;
public TTransport CreateTransport()
{
if (url == null)
{
// endpoint transport
TTransport trans = null;
if (pipe != null)
trans = new TNamedPipeClientTransport(pipe);
else
{
if (encrypted)
{
string certPath = "../keys/client.p12";
X509Certificate cert = new X509Certificate2(certPath, "thrift");
trans = new TTLSSocket(host, port, 0, cert, (o, c, chain, errors) => true, null, SslProtocols.Tls);
}
else
{
trans = new TSocket(host, port);
}
}
// layered transport
if (buffered)
trans = new TBufferedTransport(trans);
if (framed)
trans = new TFramedTransport(trans);
if (_isFirstTransport)
{
//ensure proper open/close of transport
trans.Open();
trans.Close();
_isFirstTransport = false;
}
return trans;
}
else
{
return new THttpClient(new Uri(url));
}
}
public TProtocol CreateProtocol(TTransport transport)
{
if (protocol == "compact")
return new TCompactProtocol(transport);
else if (protocol == "json")
return new TJSONProtocol(transport);
else
return new TBinaryProtocol(transport);
}
};
private const int ErrorBaseTypes = 1;
private const int ErrorStructs = 2;
private const int ErrorContainers = 4;
private const int ErrorExceptions = 8;
private const int ErrorUnknown = 64;
private class ClientTest
{
private readonly TTransport transport;
private readonly ThriftTest.Client client;
private readonly int numIterations;
private bool done;
public int ReturnCode { get; set; }
public ClientTest(TestParams param)
{
transport = param.CreateTransport();
client = new ThriftTest.Client(param.CreateProtocol(transport));
numIterations = param.numIterations;
}
public void Execute()
{
if (done)
{
Console.WriteLine("Execute called more than once");
throw new InvalidOperationException();
}
for (int i = 0; i < numIterations; i++)
{
try
{
if (!transport.IsOpen)
transport.Open();
}
catch (TTransportException ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Connect failed: " + ex.Message);
ReturnCode |= ErrorUnknown;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
continue;
}
try
{
ReturnCode |= ExecuteClientTest(client);
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
ReturnCode |= ErrorUnknown;
}
}
try
{
transport.Close();
}
catch(Exception ex)
{
Console.WriteLine("Error while closing transport");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
done = true;
}
}
public static int Execute(string[] args)
{
try
{
TestParams param = new TestParams();
int numThreads = 1;
try
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-u")
{
param.url = args[++i];
}
else if (args[i] == "-n")
{
param.numIterations = Convert.ToInt32(args[++i]);
}
else if (args[i] == "-pipe") // -pipe <name>
{
param.pipe = args[++i];
Console.WriteLine("Using named pipes transport");
}
else if (args[i].Contains("--host="))
{
param.host = args[i].Substring(args[i].IndexOf("=") + 1);
}
else if (args[i].Contains("--port="))
{
param.port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1));
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
param.buffered = true;
Console.WriteLine("Using buffered sockets");
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
param.framed = true;
Console.WriteLine("Using framed transport");
}
else if (args[i] == "-t")
{
numThreads = Convert.ToInt32(args[++i]);
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
param.protocol = "compact";
Console.WriteLine("Using compact protocol");
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
param.protocol = "json";
Console.WriteLine("Using JSON protocol");
}
else if (args[i] == "--ssl")
{
param.encrypted = true;
Console.WriteLine("Using encrypted transport");
}
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Error while parsing arguments");
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
return ErrorUnknown;
}
var tests = Enumerable.Range(0, numThreads).Select(_ => new ClientTest(param)).ToArray();
//issue tests on separate threads simultaneously
var threads = tests.Select(test => new Thread(test.Execute)).ToArray();
DateTime start = DateTime.Now;
foreach (var t in threads)
t.Start();
foreach (var t in threads)
t.Join();
Console.WriteLine("Total time: " + (DateTime.Now - start));
Console.WriteLine();
return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2);
}
catch (Exception outerEx)
{
Console.WriteLine("*** FAILED ***");
Console.WriteLine("Unexpected error");
Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
return ErrorUnknown;
}
}
public static string BytesToHex(byte[] data) {
return BitConverter.ToString(data).Replace("-", string.Empty);
}
public static byte[] PrepareTestData(bool randomDist, bool huge)
{
// huge = true tests for THRIFT-4372
byte[] retval = new byte[huge ? 0x12345 : 0x100];
int initLen = retval.Length;
// linear distribution, unless random is requested
if (!randomDist) {
for (var i = 0; i < initLen; ++i) {
retval[i] = (byte)i;
}
return retval;
}
// random distribution
for (var i = 0; i < initLen; ++i) {
retval[i] = (byte)0;
}
var rnd = new Random();
for (var i = 1; i < initLen; ++i) {
while( true) {
int nextPos = rnd.Next() % initLen;
if (retval[nextPos] == 0) {
retval[nextPos] = (byte)i;
break;
}
}
}
return retval;
}
public static int ExecuteClientTest(ThriftTest.Client client)
{
int returnCode = 0;
Console.Write("testVoid()");
client.testVoid();
Console.WriteLine(" = void");
Console.Write("testString(\"Test\")");
string s = client.testString("Test");
Console.WriteLine(" = \"" + s + "\"");
if ("Test" != s)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testBool(true)");
bool t = client.testBool((bool)true);
Console.WriteLine(" = " + t);
if (!t)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testBool(false)");
bool f = client.testBool((bool)false);
Console.WriteLine(" = " + f);
if (f)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testByte(1)");
sbyte i8 = client.testByte((sbyte)1);
Console.WriteLine(" = " + i8);
if (1 != i8)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testI32(-1)");
int i32 = client.testI32(-1);
Console.WriteLine(" = " + i32);
if (-1 != i32)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testI64(-34359738368)");
long i64 = client.testI64(-34359738368);
Console.WriteLine(" = " + i64);
if (-34359738368 != i64)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
// TODO: Validate received message
Console.Write("testDouble(5.325098235)");
double dub = client.testDouble(5.325098235);
Console.WriteLine(" = " + dub);
if (5.325098235 != dub)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("testDouble(-0.000341012439638598279)");
dub = client.testDouble(-0.000341012439638598279);
Console.WriteLine(" = " + dub);
if (-0.000341012439638598279 != dub)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
for (i32 = 0; i32 < 2; ++i32)
{
var huge = (i32 > 0);
byte[] binOut = PrepareTestData(false,huge);
Console.Write("testBinary(" + BytesToHex(binOut) + ")");
try
{
byte[] binIn = client.testBinary(binOut);
Console.WriteLine(" = " + BytesToHex(binIn));
if (binIn.Length != binOut.Length)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs)
if (binIn[ofs] != binOut[ofs])
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
}
catch (Thrift.TApplicationException ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
}
// binary equals? only with hashcode option enabled ...
Console.WriteLine("Test CrazyNesting");
if( typeof(CrazyNesting).GetMethod("Equals").DeclaringType == typeof(CrazyNesting))
{
CrazyNesting one = new CrazyNesting();
CrazyNesting two = new CrazyNesting();
one.String_field = "crazy";
two.String_field = "crazy";
one.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
if (!one.Equals(two))
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorContainers;
throw new Exception("CrazyNesting.Equals failed");
}
}
// TODO: Validate received message
Console.Write("testStruct({\"Zero\", 1, -3, -5})");
Xtruct o = new Xtruct();
o.String_thing = "Zero";
o.Byte_thing = (sbyte)1;
o.I32_thing = -3;
o.I64_thing = -5;
Xtruct i = client.testStruct(o);
Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}");
// TODO: Validate received message
Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})");
Xtruct2 o2 = new Xtruct2();
o2.Byte_thing = (sbyte)1;
o2.Struct_thing = o;
o2.I32_thing = 5;
Xtruct2 i2 = client.testNest(o2);
i = i2.Struct_thing;
Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}");
Dictionary<int, int> mapout = new Dictionary<int, int>();
for (int j = 0; j < 5; j++)
{
mapout[j] = j - 10;
}
Console.Write("testMap({");
bool first = true;
foreach (int key in mapout.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapout[key]);
}
Console.Write("})");
Dictionary<int, int> mapin = client.testMap(mapout);
Console.Write(" = {");
first = true;
foreach (int key in mapin.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapin[key]);
}
Console.WriteLine("}");
// TODO: Validate received message
List<int> listout = new List<int>();
for (int j = -2; j < 3; j++)
{
listout.Add(j);
}
Console.Write("testList({");
first = true;
foreach (int j in listout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
List<int> listin = client.testList(listout);
Console.Write(" = {");
first = true;
foreach (int j in listin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
//set
// TODO: Validate received message
THashSet<int> setout = new THashSet<int>();
for (int j = -2; j < 3; j++)
{
setout.Add(j);
}
Console.Write("testSet({");
first = true;
foreach (int j in setout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
THashSet<int> setin = client.testSet(setout);
Console.Write(" = {");
first = true;
foreach (int j in setin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
Console.Write("testEnum(ONE)");
Numberz ret = client.testEnum(Numberz.ONE);
Console.WriteLine(" = " + ret);
if (Numberz.ONE != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(TWO)");
ret = client.testEnum(Numberz.TWO);
Console.WriteLine(" = " + ret);
if (Numberz.TWO != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(THREE)");
ret = client.testEnum(Numberz.THREE);
Console.WriteLine(" = " + ret);
if (Numberz.THREE != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(FIVE)");
ret = client.testEnum(Numberz.FIVE);
Console.WriteLine(" = " + ret);
if (Numberz.FIVE != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testEnum(EIGHT)");
ret = client.testEnum(Numberz.EIGHT);
Console.WriteLine(" = " + ret);
if (Numberz.EIGHT != ret)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
Console.Write("testTypedef(309858235082523)");
long uid = client.testTypedef(309858235082523L);
Console.WriteLine(" = " + uid);
if (309858235082523L != uid)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorStructs;
}
// TODO: Validate received message
Console.Write("testMapMap(1)");
Dictionary<int, Dictionary<int, int>> mm = client.testMapMap(1);
Console.Write(" = {");
foreach (int key in mm.Keys)
{
Console.Write(key + " => {");
Dictionary<int, int> m2 = mm[key];
foreach (int k2 in m2.Keys)
{
Console.Write(k2 + " => " + m2[k2] + ", ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
// TODO: Validate received message
Insanity insane = new Insanity();
insane.UserMap = new Dictionary<Numberz, long>();
insane.UserMap[Numberz.FIVE] = 5000L;
Xtruct truck = new Xtruct();
truck.String_thing = "Truck";
truck.Byte_thing = (sbyte)8;
truck.I32_thing = 8;
truck.I64_thing = 8;
insane.Xtructs = new List<Xtruct>();
insane.Xtructs.Add(truck);
Console.Write("testInsanity()");
Dictionary<long, Dictionary<Numberz, Insanity>> whoa = client.testInsanity(insane);
Console.Write(" = {");
foreach (long key in whoa.Keys)
{
Dictionary<Numberz, Insanity> val = whoa[key];
Console.Write(key + " => {");
foreach (Numberz k2 in val.Keys)
{
Insanity v2 = val[k2];
Console.Write(k2 + " => {");
Dictionary<Numberz, long> userMap = v2.UserMap;
Console.Write("{");
if (userMap != null)
{
foreach (Numberz k3 in userMap.Keys)
{
Console.Write(k3 + " => " + userMap[k3] + ", ");
}
}
else
{
Console.Write("null");
}
Console.Write("}, ");
List<Xtruct> xtructs = v2.Xtructs;
Console.Write("{");
if (xtructs != null)
{
foreach (Xtruct x in xtructs)
{
Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, ");
}
}
else
{
Console.Write("null");
}
Console.Write("}");
Console.Write("}, ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
sbyte arg0 = 1;
int arg1 = 2;
long arg2 = long.MaxValue;
Dictionary<short, string> multiDict = new Dictionary<short, string>();
multiDict[1] = "one";
Numberz arg4 = Numberz.FIVE;
long arg5 = 5000000;
Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + "," + multiDict + "," + arg4 + "," + arg5 + ")");
Xtruct multiResponse = client.testMulti(arg0, arg1, arg2, multiDict, arg4, arg5);
Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing
+ ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n");
try
{
Console.WriteLine("testException(\"Xception\")");
client.testException("Xception");
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Xception ex)
{
if (ex.ErrorCode != 1001 || ex.Message != "Xception")
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testException(\"TException\")");
client.testException("TException");
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Thrift.TException)
{
// OK
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testException(\"ok\")");
client.testException("ok");
// OK
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testMultiException(\"Xception\", ...)");
client.testMultiException("Xception", "ignore");
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Xception ex)
{
if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception")
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testMultiException(\"Xception2\", ...)");
client.testMultiException("Xception2", "ignore");
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
catch (Xception2 ex)
{
if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2")
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
try
{
Console.WriteLine("testMultiException(\"success\", \"OK\")");
if ("OK" != client.testMultiException("success", "OK").String_thing)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
}
}
catch (Exception ex)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorExceptions;
Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
}
Stopwatch sw = new Stopwatch();
sw.Start();
Console.WriteLine("Test Oneway(1)");
client.testOneway(1);
sw.Stop();
if (sw.ElapsedMilliseconds > 1000)
{
Console.WriteLine("*** FAILED ***");
returnCode |= ErrorBaseTypes;
}
Console.Write("Test Calltime()");
var times = 50;
sw.Reset();
sw.Start();
for (int k = 0; k < times; ++k)
client.testVoid();
sw.Stop();
Console.WriteLine(" = {0} ms a testVoid() call", sw.ElapsedMilliseconds / times);
return returnCode;
}
}
}
| |
//
// GroupAddress.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
#if PORTABLE
using Encoding = Portable.Text.Encoding;
#endif
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// An address group, as specified by rfc0822.
/// </summary>
/// <remarks>
/// Group addresses are rarely used anymore. Typically, if you see a group address,
/// it will be of the form: <c>"undisclosed-recipients: ;"</c>.
/// </remarks>
public class GroupAddress : InternetAddress
{
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.GroupAddress"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="GroupAddress"/> with the specified name and list of addresses. The
/// specified text encoding is used when encoding the name according to the rules of rfc2047.
/// </remarks>
/// <param name="encoding">The character encoding to be used for encoding the name.</param>
/// <param name="name">The name of the group.</param>
/// <param name="addresses">A list of addresses.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="encoding"/> is <c>null</c>.
/// </exception>
public GroupAddress (Encoding encoding, string name, IEnumerable<InternetAddress> addresses) : base (encoding, name)
{
Members = new InternetAddressList (addresses);
Members.Changed += MembersChanged;
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.GroupAddress"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="GroupAddress"/> with the specified name and list of addresses.
/// </remarks>
/// <param name="name">The name of the group.</param>
/// <param name="addresses">A list of addresses.</param>
public GroupAddress (string name, IEnumerable<InternetAddress> addresses) : this (Encoding.UTF8, name, addresses)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.GroupAddress"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="GroupAddress"/> with the specified name. The specified
/// text encoding is used when encoding the name according to the rules of rfc2047.
/// </remarks>
/// <param name="encoding">The character encoding to be used for encoding the name.</param>
/// <param name="name">The name of the group.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="encoding"/> is <c>null</c>.
/// </exception>
public GroupAddress (Encoding encoding, string name) : base (encoding, name)
{
Members = new InternetAddressList ();
Members.Changed += MembersChanged;
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.GroupAddress"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="GroupAddress"/> with the specified name.
/// </remarks>
/// <param name="name">The name of the group.</param>
public GroupAddress (string name) : this (Encoding.UTF8, name)
{
}
/// <summary>
/// Clone the group address.
/// </summary>
/// <remarks>
/// Clones the group address.
/// </remarks>
/// <returns>The cloned group address.</returns>
public override InternetAddress Clone ()
{
return new GroupAddress (Encoding, Name, Members.Select (x => x.Clone ()));
}
/// <summary>
/// Gets the members of the group.
/// </summary>
/// <remarks>
/// Represents the member addresses of the group. Typically the member addresses
/// will be of the <see cref="MailboxAddress"/> variety, but it is possible
/// for groups to contain other groups.
/// </remarks>
/// <value>The list of members.</value>
public InternetAddressList Members {
get; private set;
}
internal override void Encode (FormatOptions options, StringBuilder builder, ref int lineLength)
{
if (builder == null)
throw new ArgumentNullException ("builder");
if (lineLength < 0)
throw new ArgumentOutOfRangeException ("lineLength");
if (!string.IsNullOrEmpty (Name)) {
string name;
if (!options.International) {
var encoded = Rfc2047.EncodePhrase (options, Encoding, Name);
name = Encoding.ASCII.GetString (encoded, 0, encoded.Length);
} else {
name = EncodeInternationalizedPhrase (Name);
}
if (lineLength + name.Length > options.MaxLineLength) {
if (name.Length > options.MaxLineLength) {
// we need to break up the name...
builder.AppendFolded (options, name, ref lineLength);
} else {
// the name itself is short enough to fit on a single line,
// but only if we write it on a line by itself
if (lineLength > 1) {
builder.LineWrap (options);
lineLength = 1;
}
lineLength += name.Length;
builder.Append (name);
}
} else {
// we can safely fit the name on this line...
lineLength += name.Length;
builder.Append (name);
}
}
builder.Append (": ");
lineLength += 2;
Members.Encode (options, builder, ref lineLength);
builder.Append (';');
lineLength++;
}
/// <summary>
/// Returns a string representation of the <see cref="GroupAddress"/>,
/// optionally encoding it for transport.
/// </summary>
/// <remarks>
/// Returns a string containing the formatted group of addresses. If the <paramref name="encode"/>
/// parameter is <c>true</c>, then the name of the group and all member addresses will be encoded
/// according to the rules defined in rfc2047, otherwise the names will not be encoded at all and
/// will therefor only be suitable for display purposes.
/// </remarks>
/// <returns>A string representing the <see cref="GroupAddress"/>.</returns>
/// <param name="options">The formatting options.</param>
/// <param name="encode">If set to <c>true</c>, the <see cref="GroupAddress"/> will be encoded.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="options"/> is <c>null</c>.
/// </exception>
public override string ToString (FormatOptions options, bool encode)
{
if (options == null)
throw new ArgumentNullException ("options");
var builder = new StringBuilder ();
if (encode) {
int lineLength = 0;
Encode (options, builder, ref lineLength);
} else {
builder.Append (Name);
builder.Append (':');
builder.Append (' ');
for (int i = 0; i < Members.Count; i++) {
if (i > 0)
builder.Append (", ");
builder.Append (Members[i]);
}
builder.Append (';');
}
return builder.ToString ();
}
#region IEquatable implementation
/// <summary>
/// Determines whether the specified <see cref="MimeKit.GroupAddress"/> is equal to the current <see cref="MimeKit.GroupAddress"/>.
/// </summary>
/// <remarks>
/// Compares two group addresses to determine if they are identical or not.
/// </remarks>
/// <param name="other">The <see cref="MimeKit.GroupAddress"/> to compare with the current <see cref="MimeKit.GroupAddress"/>.</param>
/// <returns><c>true</c> if the specified <see cref="MimeKit.GroupAddress"/> is equal to the current
/// <see cref="MimeKit.GroupAddress"/>; otherwise, <c>false</c>.</returns>
public override bool Equals (InternetAddress other)
{
var group = other as GroupAddress;
if (group == null)
return false;
return Name == group.Name && Members.Equals (group.Members);
}
#endregion
void MembersChanged (object sender, EventArgs e)
{
OnChanged ();
}
static bool TryParse (ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out GroupAddress group)
{
var flags = AddressParserFlags.AllowGroupAddress;
InternetAddress address;
if (throwOnError)
flags |= AddressParserFlags.ThrowOnError;
if (!InternetAddress.TryParse (options, text, ref index, endIndex, flags, out address)) {
group = null;
return false;
}
group = (GroupAddress) address;
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="group">The parsed group address.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, int length, out GroupAddress group)
{
ParseUtils.ValidateArguments (options, buffer, startIndex, length);
int endIndex = startIndex + length;
int index = startIndex;
if (!TryParse (options, buffer, ref index, endIndex, false, out group))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) {
group = null;
return false;
}
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="group">The parsed group address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, int length, out GroupAddress group)
{
return TryParse (ParserOptions.Default, buffer, startIndex, length, out group);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="group">The parsed group address.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, out GroupAddress group)
{
ParseUtils.ValidateArguments (options, buffer, startIndex);
int endIndex = buffer.Length;
int index = startIndex;
if (!TryParse (options, buffer, ref index, endIndex, false, out group))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) {
group = null;
return false;
}
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="group">The parsed group address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, out GroupAddress group)
{
return TryParse (ParserOptions.Default, buffer, startIndex, out group);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="group">The parsed group address.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, out GroupAddress group)
{
ParseUtils.ValidateArguments (options, buffer);
int endIndex = buffer.Length;
int index = 0;
if (!TryParse (options, buffer, ref index, endIndex, false, out group))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) {
group = null;
return false;
}
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="group">The parsed group address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
public static bool TryParse (byte[] buffer, out GroupAddress group)
{
return TryParse (ParserOptions.Default, buffer, out group);
}
/// <summary>
/// Tries to parse the given text into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="text">The text.</param>
/// <param name="group">The parsed group address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static bool TryParse (ParserOptions options, string text, out GroupAddress group)
{
if (options == null)
throw new ArgumentNullException ("options");
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
int endIndex = buffer.Length;
int index = 0;
if (!TryParse (options, buffer, ref index, endIndex, false, out group))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) {
group = null;
return false;
}
return true;
}
/// <summary>
/// Tries to parse the given text into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="text">The text.</param>
/// <param name="group">The parsed group address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static bool TryParse (string text, out GroupAddress group)
{
return TryParse (ParserOptions.Default, text, out group);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.GroupAddress"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static new GroupAddress Parse (ParserOptions options, byte[] buffer, int startIndex, int length)
{
ParseUtils.ValidateArguments (options, buffer, startIndex, length);
int endIndex = startIndex + length;
int index = startIndex;
GroupAddress group;
if (!TryParse (options, buffer, ref index, endIndex, true, out group))
throw new ParseException ("No group address found.", startIndex, startIndex);
ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true);
if (index != endIndex)
throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index);
return group;
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.GroupAddress"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static new GroupAddress Parse (byte[] buffer, int startIndex, int length)
{
return Parse (ParserOptions.Default, buffer, startIndex, length);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.GroupAddress"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/>is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static new GroupAddress Parse (ParserOptions options, byte[] buffer, int startIndex)
{
ParseUtils.ValidateArguments (options, buffer, startIndex);
int endIndex = buffer.Length;
int index = startIndex;
GroupAddress group;
if (!TryParse (options, buffer, ref index, endIndex, true, out group))
throw new ParseException ("No group address found.", startIndex, startIndex);
ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true);
if (index != endIndex)
throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index);
return group;
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.GroupAddress"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static new GroupAddress Parse (byte[] buffer, int startIndex)
{
return Parse (ParserOptions.Default, buffer, startIndex);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.GroupAddress"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static new GroupAddress Parse (ParserOptions options, byte[] buffer)
{
ParseUtils.ValidateArguments (options, buffer);
int endIndex = buffer.Length;
GroupAddress group;
int index = 0;
if (!TryParse (options, buffer, ref index, endIndex, true, out group))
throw new ParseException ("No group address found.", 0, 0);
ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true);
if (index != endIndex)
throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index);
return group;
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.GroupAddress"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static new GroupAddress Parse (byte[] buffer)
{
return Parse (ParserOptions.Default, buffer);
}
/// <summary>
/// Parses the given text into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.GroupAddress"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="text">The text.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="text"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="text"/> could not be parsed.
/// </exception>
public static new GroupAddress Parse (ParserOptions options, string text)
{
if (options == null)
throw new ArgumentNullException ("options");
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
int endIndex = buffer.Length;
GroupAddress group;
int index = 0;
if (!TryParse (options, buffer, ref index, endIndex, true, out group))
throw new ParseException ("No group address found.", 0, 0);
ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true);
if (index != endIndex)
throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index);
return group;
}
/// <summary>
/// Parses the given text into a new <see cref="MimeKit.GroupAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="GroupAddress"/>. If the address is not a group address or
/// there is more than a single group address, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.GroupAddress"/>.</returns>
/// <param name="text">The text.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="text"/> could not be parsed.
/// </exception>
public static new GroupAddress Parse (string text)
{
return Parse (ParserOptions.Default, text);
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using dnlib.DotNet.MD;
using dnlib.DotNet.Pdb;
namespace dnlib.DotNet {
/// <summary>
/// A high-level representation of a row in the AssemblyRef table
/// </summary>
public abstract class AssemblyRef : IHasCustomAttribute, IImplementation, IResolutionScope, IHasCustomDebugInformation, IAssembly, IScope {
/// <summary>
/// An assembly ref that can be used to indicate that it references the current assembly
/// when the current assembly is not known (eg. a type string without any assembly info
/// when it references a type in the current assembly).
/// </summary>
public static readonly AssemblyRef CurrentAssembly = new AssemblyRefUser("<<<CURRENT_ASSEMBLY>>>");
/// <summary>
/// The row id in its table
/// </summary>
protected uint rid;
/// <inheritdoc/>
public MDToken MDToken => new MDToken(Table.AssemblyRef, rid);
/// <inheritdoc/>
public uint Rid {
get => rid;
set => rid = value;
}
/// <inheritdoc/>
public int HasCustomAttributeTag => 15;
/// <inheritdoc/>
public int ImplementationTag => 1;
/// <inheritdoc/>
public int ResolutionScopeTag => 2;
/// <inheritdoc/>
public ScopeType ScopeType => ScopeType.AssemblyRef;
/// <inheritdoc/>
public string ScopeName => FullName;
/// <summary>
/// From columns AssemblyRef.MajorVersion, AssemblyRef.MinorVersion,
/// AssemblyRef.BuildNumber, AssemblyRef.RevisionNumber
/// </summary>
/// <exception cref="ArgumentNullException">If <paramref name="value"/> is <c>null</c></exception>
public Version Version {
get => version;
set => version = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary/>
protected Version version;
/// <summary>
/// From column AssemblyRef.Flags
/// </summary>
public AssemblyAttributes Attributes {
get => (AssemblyAttributes)attributes;
set => attributes = (int)value;
}
/// <summary>Attributes</summary>
protected int attributes;
/// <summary>
/// From column AssemblyRef.PublicKeyOrToken
/// </summary>
/// <exception cref="ArgumentNullException">If <paramref name="value"/> is <c>null</c></exception>
public PublicKeyBase PublicKeyOrToken {
get => publicKeyOrToken;
set => publicKeyOrToken = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary/>
protected PublicKeyBase publicKeyOrToken;
/// <summary>
/// From column AssemblyRef.Name
/// </summary>
public UTF8String Name {
get => name;
set => name = value;
}
/// <summary>Name</summary>
protected UTF8String name;
/// <summary>
/// From column AssemblyRef.Locale
/// </summary>
public UTF8String Culture {
get => culture;
set => culture = value;
}
/// <summary>Culture</summary>
protected UTF8String culture;
/// <summary>
/// From column AssemblyRef.HashValue
/// </summary>
public byte[] Hash {
get => hashValue;
set => hashValue = value;
}
/// <summary/>
protected byte[] hashValue;
/// <summary>
/// Gets all custom attributes
/// </summary>
public CustomAttributeCollection CustomAttributes {
get {
if (customAttributes is null)
InitializeCustomAttributes();
return customAttributes;
}
}
/// <summary/>
protected CustomAttributeCollection customAttributes;
/// <summary>Initializes <see cref="customAttributes"/></summary>
protected virtual void InitializeCustomAttributes() =>
Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null);
/// <inheritdoc/>
public bool HasCustomAttributes => CustomAttributes.Count > 0;
/// <inheritdoc/>
public int HasCustomDebugInformationTag => 15;
/// <inheritdoc/>
public bool HasCustomDebugInfos => CustomDebugInfos.Count > 0;
/// <summary>
/// Gets all custom debug infos
/// </summary>
public IList<PdbCustomDebugInfo> CustomDebugInfos {
get {
if (customDebugInfos is null)
InitializeCustomDebugInfos();
return customDebugInfos;
}
}
/// <summary/>
protected IList<PdbCustomDebugInfo> customDebugInfos;
/// <summary>Initializes <see cref="customDebugInfos"/></summary>
protected virtual void InitializeCustomDebugInfos() =>
Interlocked.CompareExchange(ref customDebugInfos, new List<PdbCustomDebugInfo>(), null);
/// <inheritdoc/>
public string FullName => FullNameToken;
/// <summary>
/// Same as <see cref="FullName"/>, except that it uses the <c>PublicKey</c> if available.
/// </summary>
public string RealFullName => Utils.GetAssemblyNameString(name, version, culture, publicKeyOrToken, Attributes);
/// <summary>
/// Gets the full name of the assembly but use a public key token
/// </summary>
public string FullNameToken => Utils.GetAssemblyNameString(name, version, culture, PublicKeyBase.ToPublicKeyToken(publicKeyOrToken), Attributes);
/// <summary>
/// Modify <see cref="attributes"/> property: <see cref="attributes"/> =
/// (<see cref="attributes"/> & <paramref name="andMask"/>) | <paramref name="orMask"/>.
/// </summary>
/// <param name="andMask">Value to <c>AND</c></param>
/// <param name="orMask">Value to OR</param>
void ModifyAttributes(AssemblyAttributes andMask, AssemblyAttributes orMask) =>
attributes = (attributes & (int)andMask) | (int)orMask;
/// <summary>
/// Set or clear flags in <see cref="attributes"/>
/// </summary>
/// <param name="set"><c>true</c> if flags should be set, <c>false</c> if flags should
/// be cleared</param>
/// <param name="flags">Flags to set or clear</param>
void ModifyAttributes(bool set, AssemblyAttributes flags) {
if (set)
attributes |= (int)flags;
else
attributes &= ~(int)flags;
}
/// <summary>
/// Gets/sets the <see cref="AssemblyAttributes.PublicKey"/> bit
/// </summary>
public bool HasPublicKey {
get => ((AssemblyAttributes)attributes & AssemblyAttributes.PublicKey) != 0;
set => ModifyAttributes(value, AssemblyAttributes.PublicKey);
}
/// <summary>
/// Gets/sets the processor architecture
/// </summary>
public AssemblyAttributes ProcessorArchitecture {
get => (AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask;
set => ModifyAttributes(~AssemblyAttributes.PA_Mask, value & AssemblyAttributes.PA_Mask);
}
/// <summary>
/// Gets/sets the processor architecture
/// </summary>
public AssemblyAttributes ProcessorArchitectureFull {
get => (AssemblyAttributes)attributes & AssemblyAttributes.PA_FullMask;
set => ModifyAttributes(~AssemblyAttributes.PA_FullMask, value & AssemblyAttributes.PA_FullMask);
}
/// <summary>
/// <c>true</c> if unspecified processor architecture
/// </summary>
public bool IsProcessorArchitectureNone => ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_None;
/// <summary>
/// <c>true</c> if neutral (PE32) architecture
/// </summary>
public bool IsProcessorArchitectureMSIL => ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_MSIL;
/// <summary>
/// <c>true</c> if x86 (PE32) architecture
/// </summary>
public bool IsProcessorArchitectureX86 => ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_x86;
/// <summary>
/// <c>true</c> if IA-64 (PE32+) architecture
/// </summary>
public bool IsProcessorArchitectureIA64 => ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_IA64;
/// <summary>
/// <c>true</c> if x64 (PE32+) architecture
/// </summary>
public bool IsProcessorArchitectureX64 => ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_AMD64;
/// <summary>
/// <c>true</c> if ARM (PE32) architecture
/// </summary>
public bool IsProcessorArchitectureARM => ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_ARM;
/// <summary>
/// <c>true</c> if eg. reference assembly (not runnable)
/// </summary>
public bool IsProcessorArchitectureNoPlatform => ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_NoPlatform;
/// <summary>
/// Gets/sets the <see cref="AssemblyAttributes.PA_Specified"/> bit
/// </summary>
public bool IsProcessorArchitectureSpecified {
get => ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Specified) != 0;
set => ModifyAttributes(value, AssemblyAttributes.PA_Specified);
}
/// <summary>
/// Gets/sets the <see cref="AssemblyAttributes.EnableJITcompileTracking"/> bit
/// </summary>
public bool EnableJITcompileTracking {
get => ((AssemblyAttributes)attributes & AssemblyAttributes.EnableJITcompileTracking) != 0;
set => ModifyAttributes(value, AssemblyAttributes.EnableJITcompileTracking);
}
/// <summary>
/// Gets/sets the <see cref="AssemblyAttributes.DisableJITcompileOptimizer"/> bit
/// </summary>
public bool DisableJITcompileOptimizer {
get => ((AssemblyAttributes)attributes & AssemblyAttributes.DisableJITcompileOptimizer) != 0;
set => ModifyAttributes(value, AssemblyAttributes.DisableJITcompileOptimizer);
}
/// <summary>
/// Gets/sets the <see cref="AssemblyAttributes.Retargetable"/> bit
/// </summary>
public bool IsRetargetable {
get => ((AssemblyAttributes)attributes & AssemblyAttributes.Retargetable) != 0;
set => ModifyAttributes(value, AssemblyAttributes.Retargetable);
}
/// <summary>
/// Gets/sets the content type
/// </summary>
public AssemblyAttributes ContentType {
get => (AssemblyAttributes)attributes & AssemblyAttributes.ContentType_Mask;
set => ModifyAttributes(~AssemblyAttributes.ContentType_Mask, value & AssemblyAttributes.ContentType_Mask);
}
/// <summary>
/// <c>true</c> if content type is <c>Default</c>
/// </summary>
public bool IsContentTypeDefault => ((AssemblyAttributes)attributes & AssemblyAttributes.ContentType_Mask) == AssemblyAttributes.ContentType_Default;
/// <summary>
/// <c>true</c> if content type is <c>WindowsRuntime</c>
/// </summary>
public bool IsContentTypeWindowsRuntime => ((AssemblyAttributes)attributes & AssemblyAttributes.ContentType_Mask) == AssemblyAttributes.ContentType_WindowsRuntime;
/// <inheritdoc/>
public override string ToString() => FullName;
}
/// <summary>
/// An AssemblyRef row created by the user and not present in the original .NET file
/// </summary>
public class AssemblyRefUser : AssemblyRef {
/// <summary>
/// Creates a reference to CLR 1.0's mscorlib
/// </summary>
public static AssemblyRefUser CreateMscorlibReferenceCLR10() => new AssemblyRefUser("mscorlib", new Version(1, 0, 3300, 0), new PublicKeyToken("b77a5c561934e089"));
/// <summary>
/// Creates a reference to CLR 1.1's mscorlib
/// </summary>
public static AssemblyRefUser CreateMscorlibReferenceCLR11() => new AssemblyRefUser("mscorlib", new Version(1, 0, 5000, 0), new PublicKeyToken("b77a5c561934e089"));
/// <summary>
/// Creates a reference to CLR 2.0's mscorlib
/// </summary>
public static AssemblyRefUser CreateMscorlibReferenceCLR20() => new AssemblyRefUser("mscorlib", new Version(2, 0, 0, 0), new PublicKeyToken("b77a5c561934e089"));
/// <summary>
/// Creates a reference to CLR 4.0's mscorlib
/// </summary>
public static AssemblyRefUser CreateMscorlibReferenceCLR40() => new AssemblyRefUser("mscorlib", new Version(4, 0, 0, 0), new PublicKeyToken("b77a5c561934e089"));
/// <summary>
/// Default constructor
/// </summary>
public AssemblyRefUser()
: this(UTF8String.Empty) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Simple name</param>
/// <exception cref="ArgumentNullException">If any of the args is invalid</exception>
public AssemblyRefUser(UTF8String name)
: this(name, new Version(0, 0, 0, 0)) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Simple name</param>
/// <param name="version">Version</param>
/// <exception cref="ArgumentNullException">If any of the args is invalid</exception>
public AssemblyRefUser(UTF8String name, Version version)
: this(name, version, new PublicKey()) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Simple name</param>
/// <param name="version">Version</param>
/// <param name="publicKey">Public key or public key token</param>
/// <exception cref="ArgumentNullException">If any of the args is invalid</exception>
public AssemblyRefUser(UTF8String name, Version version, PublicKeyBase publicKey)
: this(name, version, publicKey, UTF8String.Empty) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Simple name</param>
/// <param name="version">Version</param>
/// <param name="publicKey">Public key or public key token</param>
/// <param name="locale">Locale</param>
/// <exception cref="ArgumentNullException">If any of the args is invalid</exception>
public AssemblyRefUser(UTF8String name, Version version, PublicKeyBase publicKey, UTF8String locale) {
if (name is null)
throw new ArgumentNullException(nameof(name));
if (locale is null)
throw new ArgumentNullException(nameof(locale));
this.name = name;
this.version = version ?? throw new ArgumentNullException(nameof(version));
publicKeyOrToken = publicKey;
culture = locale;
attributes = (int)(publicKey is PublicKey ? AssemblyAttributes.PublicKey : AssemblyAttributes.None);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="asmName">Assembly name info</param>
/// <exception cref="ArgumentNullException">If <paramref name="asmName"/> is <c>null</c></exception>
public AssemblyRefUser(AssemblyName asmName)
: this(new AssemblyNameInfo(asmName)) => attributes = (int)asmName.Flags;
/// <summary>
/// Constructor
/// </summary>
/// <param name="assembly">Assembly</param>
public AssemblyRefUser(IAssembly assembly) {
if (assembly is null)
throw new ArgumentNullException("asmName");
version = assembly.Version ?? new Version(0, 0, 0, 0);
publicKeyOrToken = assembly.PublicKeyOrToken;
name = UTF8String.IsNullOrEmpty(assembly.Name) ? UTF8String.Empty : assembly.Name;
culture = assembly.Culture;
attributes = (int)((publicKeyOrToken is PublicKey ? AssemblyAttributes.PublicKey : AssemblyAttributes.None) | assembly.ContentType);
}
}
/// <summary>
/// Created from a row in the AssemblyRef table
/// </summary>
sealed class AssemblyRefMD : AssemblyRef, IMDTokenProviderMD {
/// <summary>The module where this instance is located</summary>
readonly ModuleDefMD readerModule;
readonly uint origRid;
/// <inheritdoc/>
public uint OrigRid => origRid;
/// <inheritdoc/>
protected override void InitializeCustomAttributes() {
var list = readerModule.Metadata.GetCustomAttributeRidList(Table.AssemblyRef, origRid);
var tmp = new CustomAttributeCollection(list.Count, list, (list2, index) => readerModule.ReadCustomAttribute(list[index]));
Interlocked.CompareExchange(ref customAttributes, tmp, null);
}
/// <inheritdoc/>
protected override void InitializeCustomDebugInfos() {
var list = new List<PdbCustomDebugInfo>();
readerModule.InitializeCustomDebugInfos(new MDToken(MDToken.Table, origRid), new GenericParamContext(), list);
Interlocked.CompareExchange(ref customDebugInfos, list, null);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="readerModule">The module which contains this <c>AssemblyRef</c> row</param>
/// <param name="rid">Row ID</param>
/// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception>
/// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception>
public AssemblyRefMD(ModuleDefMD readerModule, uint rid) {
#if DEBUG
if (readerModule is null)
throw new ArgumentNullException("readerModule");
if (readerModule.TablesStream.AssemblyRefTable.IsInvalidRID(rid))
throw new BadImageFormatException($"AssemblyRef rid {rid} does not exist");
#endif
origRid = rid;
this.rid = rid;
this.readerModule = readerModule;
bool b = readerModule.TablesStream.TryReadAssemblyRefRow(origRid, out var row);
Debug.Assert(b);
version = new Version(row.MajorVersion, row.MinorVersion, row.BuildNumber, row.RevisionNumber);
attributes = (int)row.Flags;
var pkData = readerModule.BlobStream.Read(row.PublicKeyOrToken);
if ((attributes & (uint)AssemblyAttributes.PublicKey) != 0)
publicKeyOrToken = new PublicKey(pkData);
else
publicKeyOrToken = new PublicKeyToken(pkData);
name = readerModule.StringsStream.ReadNoNull(row.Name);
culture = readerModule.StringsStream.ReadNoNull(row.Locale);
hashValue = readerModule.BlobStream.Read(row.HashValue);
}
}
}
| |
//
// PrimarySource.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.Jobs;
using Hyena.Data;
using Hyena.Query;
using Hyena.Data.Sqlite;
using Hyena.Collections;
using Banshee.Base;
using Banshee.Preferences;
using Banshee.ServiceStack;
using Banshee.Configuration;
using Banshee.Sources;
using Banshee.Playlist;
using Banshee.SmartPlaylist;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Query;
namespace Banshee.Sources
{
public class TrackEventArgs : EventArgs
{
private DateTime when;
public DateTime When {
get { return when; }
}
private QueryField [] changed_fields;
public QueryField [] ChangedFields {
get { return changed_fields; }
}
public TrackEventArgs ()
{
when = DateTime.Now;
}
public TrackEventArgs (params QueryField [] fields) : this ()
{
changed_fields = fields;
}
}
public delegate bool TrackEqualHandler (DatabaseTrackInfo a, TrackInfo b);
public delegate object TrackExternalObjectHandler (DatabaseTrackInfo a);
public delegate string TrackArtworkIdHandler (DatabaseTrackInfo a);
public abstract class PrimarySource : DatabaseSource, IDisposable
{
#region Functions that let us override some behavior of our DatabaseTrackInfos
public TrackEqualHandler TrackEqualHandler { get; protected set; }
public TrackInfo.IsPlayingHandler TrackIsPlayingHandler { get; protected set; }
public TrackExternalObjectHandler TrackExternalObjectHandler { get; protected set; }
public TrackArtworkIdHandler TrackArtworkIdHandler { get; protected set; }
#endregion
protected ErrorSource error_source;
protected bool error_source_visible = false;
protected string remove_range_sql = @"
INSERT INTO CoreRemovedTracks (DateRemovedStamp, TrackID, Uri)
SELECT ?, TrackID, " + BansheeQuery.UriField.Column + @"
FROM CoreTracks WHERE TrackID IN (SELECT {0});
DELETE FROM CoreTracks WHERE TrackID IN (SELECT {0})";
protected HyenaSqliteCommand remove_list_command = new HyenaSqliteCommand (String.Format (@"
INSERT INTO CoreRemovedTracks (DateRemovedStamp, TrackID, Uri)
SELECT ?, TrackID, {0} FROM CoreTracks WHERE TrackID IN (SELECT ItemID FROM CoreCache WHERE ModelID = ?);
DELETE FROM CoreTracks WHERE TrackID IN (SELECT ItemID FROM CoreCache WHERE ModelID = ?)
", BansheeQuery.UriField.Column));
protected HyenaSqliteCommand prune_artists_albums_command = new HyenaSqliteCommand (@"
DELETE FROM CoreAlbums WHERE AlbumID NOT IN (SELECT AlbumID FROM CoreTracks);
DELETE FROM CoreArtists WHERE
NOT EXISTS (SELECT 1 FROM CoreTracks WHERE CoreTracks.ArtistID = CoreArtists.ArtistID)
AND NOT EXISTS (SELECT 1 FROM CoreAlbums WHERE CoreAlbums.ArtistID = CoreArtists.ArtistID)
");
protected HyenaSqliteCommand purge_tracks_command = new HyenaSqliteCommand (@"
DELETE FROM CoreTracks WHERE PrimarySourceId = ?
");
private SchemaEntry<bool> expanded_schema;
public SchemaEntry<bool> ExpandedSchema {
get { return expanded_schema; }
}
private long dbid;
public long DbId {
get {
if (dbid > 0) {
return dbid;
}
dbid = ServiceManager.DbConnection.Query<long> ("SELECT PrimarySourceID FROM CorePrimarySources WHERE StringID = ?", UniqueId);
if (dbid == 0) {
dbid = ServiceManager.DbConnection.Execute ("INSERT INTO CorePrimarySources (StringID, IsTemporary) VALUES (?, ?)", UniqueId, IsTemporary);
} else {
SavedCount = ServiceManager.DbConnection.Query<int> ("SELECT CachedCount FROM CorePrimarySources WHERE PrimarySourceID = ?", dbid);
IsTemporary = ServiceManager.DbConnection.Query<bool> ("SELECT IsTemporary FROM CorePrimarySources WHERE PrimarySourceID = ?", dbid);
}
if (dbid == 0) {
throw new ApplicationException ("dbid could not be resolved, this should never happen");
}
return dbid;
}
}
private bool supports_playlists = true;
public virtual bool SupportsPlaylists {
get { return supports_playlists; }
protected set { supports_playlists = value; }
}
public virtual bool PlaylistsReadOnly {
get { return false; }
}
public ErrorSource ErrorSource {
get {
if (error_source == null) {
error_source = new ErrorSource (Catalog.GetString ("Errors"));
ErrorSource.Updated += OnErrorSourceUpdated;
OnErrorSourceUpdated (null, null);
}
return error_source;
}
}
private bool is_local = false;
public bool IsLocal {
get { return is_local; }
protected set { is_local = value; }
}
private static SourceSortType[] sort_types = new SourceSortType[] {
SortNameAscending,
SortSizeAscending,
SortSizeDescending
};
public override SourceSortType[] ChildSortTypes {
get { return sort_types; }
}
public override SourceSortType DefaultChildSort {
get { return SortNameAscending; }
}
public delegate void TrackEventHandler (Source sender, TrackEventArgs args);
public event TrackEventHandler TracksAdded;
public event TrackEventHandler TracksChanged;
public event TrackEventHandler TracksDeleted;
private static Dictionary<long, PrimarySource> primary_sources = new Dictionary<long, PrimarySource> ();
public static PrimarySource GetById (long id)
{
return (primary_sources.ContainsKey (id)) ? primary_sources[id] : null;
}
public virtual string BaseDirectory {
get { return null; }
protected set { base_dir_with_sep = null; }
}
private string base_dir_with_sep;
public string BaseDirectoryWithSeparator {
get { return base_dir_with_sep ?? (base_dir_with_sep = BaseDirectory + System.IO.Path.DirectorySeparatorChar); }
}
protected PrimarySource (string generic_name, string name, string id, int order) : this (generic_name, name, id, order, false)
{
}
protected PrimarySource (string generic_name, string name, string id, int order, bool is_temp) : base (generic_name, name, id, order)
{
Properties.SetString ("SortChildrenActionLabel", Catalog.GetString ("Sort Playlists By"));
IsTemporary = is_temp;
PrimarySourceInitialize ();
}
protected PrimarySource () : base ()
{
}
// Translators: this is a noun, referring to the harddisk
private string storage_name = Catalog.GetString ("Drive");
public string StorageName {
get { return storage_name; }
protected set { storage_name = value; }
}
public override bool? AutoExpand {
get { return ExpandedSchema.Get (); }
}
public override bool Expanded {
get { return ExpandedSchema.Get (); }
set {
ExpandedSchema.Set (value);
base.Expanded = value;
}
}
public PathPattern PathPattern { get; private set; }
protected void SetFileNamePattern (PathPattern pattern)
{
PathPattern = pattern;
var file_system = PreferencesPage.FindOrAdd (new Section ("file-system", Catalog.GetString ("File Organization"), 5));
file_system.Add (new SchemaPreference<string> (pattern.FolderSchema, Catalog.GetString ("Folder hie_rarchy")));
file_system.Add (new SchemaPreference<string> (pattern.FileSchema, Catalog.GetString ("File _name")));
}
public virtual void Dispose ()
{
PurgeSelfIfTemporary ();
if (Application.ShuttingDown)
return;
DatabaseTrackInfo track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (track != null && track.PrimarySourceId == this.DbId) {
ServiceManager.PlayerEngine.Close ();
}
ClearChildSources ();
Remove ();
}
protected override void Initialize ()
{
base.Initialize ();
PrimarySourceInitialize ();
}
private void PrimarySourceInitialize ()
{
// Scope the tracks to this primary source
DatabaseTrackModel.AddCondition (String.Format ("CoreTracks.PrimarySourceID = {0}", DbId));
primary_sources[DbId] = this;
// If there was a crash, tracks can be left behind, for example in DaapSource.
// Temporary playlists are cleaned up by the PlaylistSource.LoadAll call below
if (IsTemporary && SavedCount > 0) {
PurgeTracks ();
}
// Load our playlists and smart playlists
foreach (PlaylistSource pl in PlaylistSource.LoadAll (this)) {
AddChildSource (pl);
}
int sp_count = 0;
foreach (SmartPlaylistSource pl in SmartPlaylistSource.LoadAll (this)) {
AddChildSource (pl);
sp_count++;
}
// Create default smart playlists if we haven't done it ever before, and if the
// user has zero smart playlists.
if (!HaveCreatedSmartPlaylists) {
if (sp_count == 0) {
foreach (SmartPlaylistDefinition def in DefaultSmartPlaylists) {
SmartPlaylistSource pl = def.ToSmartPlaylistSource (this);
pl.Save ();
AddChildSource (pl);
pl.RefreshAndReload ();
sp_count++;
}
}
// Only save it if we already had some smart playlists, or we actually created some (eg not
// if we didn't have any and the list of default ones is empty atm).
if (sp_count > 0)
HaveCreatedSmartPlaylists = true;
}
expanded_schema = new SchemaEntry<bool> (
String.Format ("sources.{0}", ParentConfigurationId), "expanded", true, "Is source expanded", "Is source expanded"
);
}
private bool HaveCreatedSmartPlaylists {
get { return DatabaseConfigurationClient.Client.Get<bool> ("HaveCreatedSmartPlaylists", UniqueId, false); }
set { DatabaseConfigurationClient.Client.Set<bool> ("HaveCreatedSmartPlaylists", UniqueId, value); }
}
public override void Save ()
{
ServiceManager.DbConnection.Execute (
"UPDATE CorePrimarySources SET CachedCount = ? WHERE PrimarySourceID = ?",
Count, DbId
);
}
public virtual void UpdateMetadata (DatabaseTrackInfo track)
{
}
public virtual void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
{
Log.WarningFormat ("CopyTrackTo not implemented for source {0}", this);
}
internal void NotifyTracksAdded ()
{
OnTracksAdded ();
}
internal void NotifyTracksChanged (params QueryField [] fields)
{
OnTracksChanged (fields);
}
// TODO replace this public method with a 'transaction'-like system
public void NotifyTracksChanged ()
{
OnTracksChanged ();
}
public void NotifyTracksDeleted ()
{
OnTracksDeleted ();
}
protected void OnErrorSourceUpdated (object o, EventArgs args)
{
lock (error_source) {
if (error_source.Count > 0 && !error_source_visible) {
error_source_visible = true;
AddChildSource (error_source);
} else if (error_source.Count <= 0 && error_source_visible) {
error_source_visible = false;
RemoveChildSource (error_source);
}
}
}
public virtual IEnumerable<SmartPlaylistDefinition> DefaultSmartPlaylists {
get { yield break; }
}
public virtual IEnumerable<SmartPlaylistDefinition> NonDefaultSmartPlaylists {
get { yield break; }
}
public IEnumerable<SmartPlaylistDefinition> PredefinedSmartPlaylists {
get {
foreach (SmartPlaylistDefinition def in DefaultSmartPlaylists)
yield return def;
foreach (SmartPlaylistDefinition def in NonDefaultSmartPlaylists)
yield return def;
}
}
public override bool CanSearch {
get { return true; }
}
protected override void OnTracksAdded ()
{
ThreadAssist.SpawnFromMain (delegate {
Reload ();
TrackEventHandler handler = TracksAdded;
if (handler != null) {
handler (this, new TrackEventArgs ());
}
});
}
protected override void OnTracksChanged (params QueryField [] fields)
{
ThreadAssist.SpawnFromMain (delegate {
if (NeedsReloadWhenFieldsChanged (fields)) {
Reload ();
} else {
InvalidateCaches ();
}
System.Threading.Thread.Sleep (150);
TrackEventHandler handler = TracksChanged;
if (handler != null) {
handler (this, new TrackEventArgs (fields));
}
});
}
protected override void OnTracksDeleted ()
{
ThreadAssist.SpawnFromMain (delegate {
PruneArtistsAlbums ();
Reload ();
TrackEventHandler handler = TracksDeleted;
if (handler != null) {
handler (this, new TrackEventArgs ());
}
SkipTrackIfRemoved ();
});
}
protected override void OnTracksRemoved ()
{
OnTracksDeleted ();
}
protected virtual void PurgeSelfIfTemporary ()
{
if (!IsTemporary) {
return;
}
PlaylistSource.ClearTemporary (this);
PurgeTracks ();
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
DELETE FROM CorePrimarySources WHERE PrimarySourceId = ?"),
DbId);
}
protected virtual void PurgeTracks ()
{
ServiceManager.DbConnection.Execute (purge_tracks_command, DbId);
}
protected override void RemoveTrackRange (DatabaseTrackListModel model, RangeCollection.Range range)
{
ServiceManager.DbConnection.Execute (
String.Format (remove_range_sql, model.TrackIdsSql),
DateTime.Now,
model.CacheId, range.Start, range.End - range.Start + 1,
model.CacheId, range.Start, range.End - range.Start + 1
);
}
public void DeleteAllTracks (AbstractPlaylistSource source)
{
if (source.PrimarySource != this) {
Log.WarningFormat ("Cannot delete all tracks from {0} via primary source {1}", source, this);
return;
}
if (source.Count < 1)
return;
var list = CachedList<DatabaseTrackInfo>.CreateFromModel (source.DatabaseTrackModel);
ThreadAssist.SpawnFromMain (delegate {
DeleteTrackList (list);
});
}
public override void DeleteTracks (DatabaseTrackListModel model, Selection selection)
{
if (model == null || model.Count < 1) {
return;
}
var list = CachedList<DatabaseTrackInfo>.CreateFromModelAndSelection (model, selection);
ThreadAssist.SpawnFromMain (delegate {
DeleteTrackList (list);
});
}
protected virtual void DeleteTrackList (CachedList<DatabaseTrackInfo> list)
{
is_deleting = true;
DeleteTrackJob.Total += list.Count;
var skip_deletion = new List<DatabaseTrackInfo> ();
// Remove from file system
foreach (DatabaseTrackInfo track in list) {
if (track == null) {
DeleteTrackJob.Completed++;
continue;
}
if (DeleteTrackJob.IsCancelRequested) {
skip_deletion.Add (track);
continue;
}
try {
DeleteTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
if (!DeleteTrack (track)) {
skip_deletion.Add (track);
}
} catch (Exception e) {
Log.Error (e);
ErrorSource.AddMessage (e.Message, track.Uri.ToString ());
}
DeleteTrackJob.Completed++;
if (DeleteTrackJob.Completed % 10 == 0 && !DeleteTrackJob.IsFinished) {
OnTracksDeleted ();
}
}
if (!DeleteTrackJob.IsFinished || DeleteTrackJob.IsCancelRequested) {
delete_track_job.Finish ();
}
delete_track_job = null;
is_deleting = false;
if (skip_deletion.Count > 0) {
list.Remove (skip_deletion);
skip_deletion.Clear ();
}
// Remove from database
if (list.Count > 0) {
ServiceManager.DbConnection.Execute (remove_list_command, DateTime.Now, list.CacheId, list.CacheId);
}
ThreadAssist.ProxyToMain (delegate {
OnTracksDeleted ();
OnUserNotifyUpdated ();
OnUpdated ();
});
}
protected virtual bool DeleteTrack (DatabaseTrackInfo track)
{
if (!track.Uri.IsLocalPath)
throw new Exception ("Cannot delete a non-local resource: " + track.Uri.Scheme);
try {
Banshee.IO.Utilities.DeleteFileTrimmingParentDirectories (track.Uri);
} catch (System.IO.FileNotFoundException) {
} catch (System.IO.DirectoryNotFoundException) {
}
return true;
}
public override bool AcceptsInputFromSource (Source source)
{
return base.AcceptsInputFromSource (source) && source.Parent != this
&& (source.Parent is PrimarySource || source is PrimarySource)
&& !(source.Parent is Banshee.Library.LibrarySource);
}
public override bool AddSelectedTracks (Source source, Selection selection)
{
if (!AcceptsInputFromSource (source))
return false;
DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel;
// Store a snapshot of the current selection
CachedList<DatabaseTrackInfo> cached_list = CachedList<DatabaseTrackInfo>.CreateFromModelAndSelection (model, selection);
if (ThreadAssist.InMainThread) {
System.Threading.ThreadPool.QueueUserWorkItem (AddTrackList, cached_list);
} else {
AddTrackList (cached_list);
}
return true;
}
public long GetTrackIdForUri (string uri)
{
return DatabaseTrackInfo.GetTrackIdForUri (new SafeUri (uri), DbId);
}
private bool is_adding;
public bool IsAdding {
get { return is_adding; }
}
private bool is_deleting;
public bool IsDeleting {
get { return is_deleting; }
}
protected virtual void AddTrackAndIncrementCount (DatabaseTrackInfo track)
{
AddTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
AddTrack (track);
IncrementAddedTracks ();
}
protected virtual void AddTrackList (object cached_list)
{
CachedList<DatabaseTrackInfo> list = cached_list as CachedList<DatabaseTrackInfo>;
is_adding = true;
AddTrackJob.Total += list.Count;
foreach (DatabaseTrackInfo track in list) {
if (AddTrackJob.IsCancelRequested) {
AddTrackJob.Finish ();
IncrementAddedTracks ();
break;
}
if (track == null) {
IncrementAddedTracks ();
continue;
}
try {
AddTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
AddTrackAndIncrementCount (track);
} catch (Exception e) {
IncrementAddedTracks ();
Log.Error (e);
ErrorSource.AddMessage (e.Message, track.Uri.ToString ());
}
}
if (!AddTrackJob.IsFinished) {
AddTrackJob.Finish ();
}
add_track_job = null;
is_adding = false;
}
protected void IncrementAddedTracks ()
{
bool finished = false, notify = false;
lock (this) {
AddTrackJob.Completed++;
if (add_track_job.IsFinished) {
finished = true;
} else {
if (add_track_job.Completed % 10 == 0)
notify = true;
}
}
if (finished) {
is_adding = false;
}
if (notify || finished) {
OnTracksAdded ();
if (finished) {
ThreadAssist.ProxyToMain (OnUserNotifyUpdated);
}
}
}
private bool delay_add_job = true;
protected bool DelayAddJob {
get { return delay_add_job; }
set { delay_add_job = value; }
}
private bool delay_delete_job = true;
protected bool DelayDeleteJob {
get { return delay_delete_job; }
set { delay_delete_job = value; }
}
private BatchUserJob add_track_job;
protected BatchUserJob AddTrackJob {
get {
lock (this) {
if (add_track_job == null) {
add_track_job = new BatchUserJob (String.Format (Catalog.GetString (
"Adding {0} of {1} to {2}"), "{0}", "{1}", Name),
Properties.GetStringList ("Icon.Name"));
add_track_job.SetResources (Resource.Cpu, Resource.Database, Resource.Disk);
add_track_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped;
add_track_job.DelayShow = DelayAddJob;
add_track_job.CanCancel = true;
add_track_job.Register ();
}
}
return add_track_job;
}
}
private BatchUserJob delete_track_job;
protected BatchUserJob DeleteTrackJob {
get {
lock (this) {
if (delete_track_job == null) {
delete_track_job = new BatchUserJob (String.Format (Catalog.GetString (
"Deleting {0} of {1} From {2}"), "{0}", "{1}", Name),
Properties.GetStringList ("Icon.Name"));
delete_track_job.SetResources (Resource.Cpu, Resource.Database);
delete_track_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped;
delete_track_job.DelayShow = DelayDeleteJob;
delete_track_job.CanCancel = true;
delete_track_job.Register ();
}
}
return delete_track_job;
}
}
protected override void PruneArtistsAlbums ()
{
ServiceManager.DbConnection.Execute (prune_artists_albums_command);
base.PruneArtistsAlbums ();
DatabaseAlbumInfo.Reset ();
DatabaseArtistInfo.Reset ();
}
}
}
| |
using System;
using System.Windows.Forms;
using PrimerProForms;
using PrimerProObjects;
using GenLib;
namespace PrimerProSearch
{
/// <summary>
/// Frequenncy Search in Word List
/// </summary>
public class FrequencyWLSearch : Search
{
//Search parameters
private bool m_IgnoreSightWords; // Ignore Sight Words
private bool m_IgnoreTone; // Ignore Tone Marks
private bool m_DisplayPercentages; // Display percentage
private SearchOptions m_SearchOptions; // Search options filters
private string m_Title; // Search title
private Settings m_Settings; // Application settings
private PSTable m_PSTable; // Parts of speech
private GraphemeInventory m_GraphemeInventory; // Grapheme Inventory
// Search Definition tags
private const string kIgnoreSightWords = "IgnoreSightWords";
private const string kIgnoreTone = "IgnoreTone";
private const string kDisplayPercentages = "DisplayPercentages";
//private const string kTitle = "Frequency Count in Word List";
public FrequencyWLSearch(int number, Settings s)
: base(number, SearchDefinition.kFrequencyWL)
{
m_IgnoreSightWords = false;
m_IgnoreSightWords = false;
m_DisplayPercentages = false;
m_SearchOptions = null;
m_Settings = s;
//m_Title = FrequencyWLSearch.kTitle;
m_Title = m_Settings.LocalizationTable.GetMessage("FrequencyWLSearchT");
if (m_Title == "")
m_Title = "Frequency Count from Word List";
m_PSTable = m_Settings.PSTable;
m_GraphemeInventory = m_Settings.GraphemeInventory;
}
public bool IgnoreSightWords
{
get {return m_IgnoreSightWords;}
set {m_IgnoreSightWords = value;}
}
public bool IgnoreTone
{
get { return m_IgnoreTone; }
set { m_IgnoreTone = value; }
}
public bool DisplayPercentages
{
get {return m_DisplayPercentages;}
set { m_DisplayPercentages = value; }
}
public SearchOptions SearchOptions
{
get {return m_SearchOptions;}
set {m_SearchOptions = value;}
}
public string Title
{
get {return m_Title;}
}
public PSTable PSTable
{
get {return m_PSTable;}
}
public GraphemeInventory GraphemeInventory
{
get {return m_GraphemeInventory;}
}
public bool SetupSearch()
{
bool flag = false;
//FormFrequencyWL fpb = new FormFrequencyWL(this.PSTable);
FormFrequencyWL form = new FormFrequencyWL(m_PSTable,
m_Settings.LocalizationTable, m_Settings.OptionSettings.UILanguage);
DialogResult dr;
dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
this.IgnoreSightWords = form.IgnoreSightWords;
this.IgnoreTone = form.IgnoreTone;
this.DisplayPercentages = form.DisplayPercentages;
this.SearchOptions = form.SearchOptions;
SearchDefinition sd = new SearchDefinition(SearchDefinition.kFrequencyWL);
SearchDefinitionParm sdp = null;
this.SearchDefinition = sd;
if (form.IgnoreSightWords)
{
sdp = new SearchDefinitionParm(FrequencyWLSearch.kIgnoreSightWords);
sd.AddSearchParm(sdp);
}
if (form.IgnoreTone)
{
sdp = new SearchDefinitionParm(FrequencyWLSearch.kIgnoreTone);
sd.AddSearchParm(sdp);
}
if (form.DisplayPercentages)
{
sdp = new SearchDefinitionParm(FrequencyWLSearch.kDisplayPercentages);
sd.AddSearchParm(sdp);
}
if (form.SearchOptions != null)
sd.AddSearchOptions(this.SearchOptions);
this.SearchDefinition = sd;
flag = true;
}
return flag;
}
public bool SetupSearch(SearchDefinition sd)
{
bool flag = true;
string strTag = "";
SearchOptions so = new SearchOptions(m_PSTable);
for (int i = 0; i < sd.SearchParmsCount(); i++)
{
strTag = sd.GetSearchParmAt(i).GetTag();
if (strTag == FrequencyWLSearch.kIgnoreSightWords)
this.IgnoreSightWords = true;
if (strTag == FrequencyWLSearch.kIgnoreTone)
this.IgnoreTone = true;
if (strTag == FrequencyWLSearch.kDisplayPercentages)
this.DisplayPercentages = true;
}
this.SearchOptions = sd.MakeSearchOptions(so);
this.SearchDefinition = sd;
return flag;
}
public string BuildResults()
{
string strText = "";
string strSN = "";
string str = "";
if (this.SearchNumber > 0)
{
strSN = Search.TagSN + this.SearchNumber.ToString().Trim();
strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine;
}
strText += this.Title + Environment.NewLine + Environment.NewLine;
strText += this.SearchResults;
strText += Environment.NewLine;
//strText += this.SearchCount.ToString() + " entries found" + Environment.NewLine;
str = m_Settings.LocalizationTable.GetMessage("Search2");
if (str == "")
str = "entries found";
strText += this.SearchCount.ToString() + Constants.Space + str + Environment.NewLine;
if (this.SearchNumber > 0)
strText += Search.TagOpener + Search.TagForwardSlash + strSN
+ Search.TagCloser;
return strText;
}
//public FrequencyWLSearch XExecuteFrequencySearch(WordList wl)
//{
// Word wrd = null;
// Consonant cns = null;
// Vowel vwl = null;
// Tone tone = null;
// Syllograph syllograph = null;
// string strSymbol = "";
// string strText = "";
// // Process consonants
// for (int i = 0; i < this.GraphemeInventory.ConsonantCount(); i++)
// {
// cns = this.GraphemeInventory.GetConsonant(i);
// strSymbol = cns.Symbol;
// cns.InitCountInWordList();
// for (int j = 0; j < wl.WordCount(); j++)
// {
// wrd = wl.GetWord(j);
// if (this.SearchOptions != null)
// {
// if ((this.SearchOptions.MatchesWord(wrd))
// && (this.SearchOptions.MatchesPosition(wrd, strSymbol)))
// {
// if (this.SearchOptions.IsRootOnly)
// {
// if (wrd.Root.IsInRoot(strSymbol))
// cns.IncrCountInWordList();
// }
// else
// {
// if (wrd.ContainInWord(strSymbol))
// cns.IncrCountInWordList();
// }
// }
// }
// else
// {
// if (wrd.ContainInWord(strSymbol))
// cns.IncrCountInWordList();
// }
// }
// }
// //Process vowels
// for (int i = 0; i < this.GraphemeInventory.VowelCount(); i++)
// {
// vwl = this.GraphemeInventory.GetVowel(i);
// strSymbol = vwl.Symbol;
// vwl.InitCountInWordList();
// for (int j = 0; j < wl.WordCount(); j++)
// {
// wrd = wl.GetWord(j);
// if (this.SearchOptions != null)
// {
// if ((this.SearchOptions.MatchesWord(wrd))
// && (this.SearchOptions.MatchesPosition(wrd, strSymbol)))
// {
// if (wrd.ContainInWord(strSymbol))
// vwl.IncrCountInWordList();
// }
// }
// else
// {
// if (wrd.ContainInWord(strSymbol))
// vwl.IncrCountInWordList();
// }
// }
// }
// //Process Tones
// for (int i = 0; i < this.GraphemeInventory.ToneCount(); i++)
// {
// tone = this.GraphemeInventory.GetTone(i);
// strSymbol = tone.Symbol;
// tone.InitCountInWordList();
// for (int j = 0; j < wl.WordCount(); j++)
// {
// wrd = wl.GetWord(j);
// if (this.SearchOptions != null)
// {
// if ((this.SearchOptions.MatchesWord(wrd))
// && (this.SearchOptions.MatchesPosition(wrd, strSymbol)))
// {
// if (this.SearchOptions.IsRootOnly)
// {
// if (wrd.Root.IsInRoot(strSymbol))
// tone.IncrCountInWordList();
// }
// else
// {
// if (wrd.ContainInWord(strSymbol))
// tone.IncrCountInWordList();
// }
// }
// }
// else //no search options
// {
// if (wrd.ContainInWord(strSymbol))
// tone.IncrCountInWordList();
// }
// }
// }
// //Process Syllabaries
// for (int i = 0; i < this.GraphemeInventory.SyllographCount(); i++)
// {
// syllograph = this.GraphemeInventory.GetSyllograph(i);
// strSymbol = syllograph.Symbol;
// syllograph.InitCountInWordList();
// for (int j = 0; j < wl.WordCount(); j++)
// {
// wrd = wl.GetWord(j);
// if (this.SearchOptions != null)
// {
// if ((this.SearchOptions.MatchesWord(wrd))
// && (this.SearchOptions.MatchesPosition(wrd, strSymbol)))
// {
// if (this.SearchOptions.IsRootOnly)
// {
// if (wrd.Root.IsInRoot(strSymbol))
// syllograph.IncrCountInWordList();
// }
// else
// {
// if (wrd.ContainInWord(strSymbol))
// syllograph.IncrCountInWordList();
// }
// }
// }
// else
// {
// if (wrd.ContainInWord(strSymbol))
// syllograph.IncrCountInWordList();
// }
// }
// }
// //strText += "Consonants" + Environment.NewLine;
// strText += m_Settings.LocalizationTable.GetMessage("FrequencyWLSearch1") + Environment.NewLine;
// if (this.DisplayPercentages)
// strText += this.GraphemeInventory.SortedConsonantPercentagesInWordList();
// else strText += this.GraphemeInventory.SortedConsonantCountsInWordList();
// strText += Environment.NewLine;
// //strText += "Vowels" + Environment.NewLine;
// strText += m_Settings.LocalizationTable.GetMessage("FrequencyWLSearch2") + Environment.NewLine;
// if (this.DisplayPercentages)
// strText += this.GraphemeInventory.SortedVowelPercentagesInWordList();
// else strText += this.GraphemeInventory.SortedVowelCountsInWordList();
// strText += Environment.NewLine;
// //strText += "Tones" + Environment.NewLine;
// strText += m_Settings.LocalizationTable.GetMessage("FrequencyWLSearch3") + Environment.NewLine;
// if (this.DisplayPercentages)
// strText += this.GraphemeInventory.SortedTonePercentsgesInWordList();
// else strText += this.GraphemeInventory.SortedToneCountsInWordList();
// strText += Environment.NewLine;
// //strText += "Syllographs" + Environment.NewLine;
// strText += m_Settings.LocalizationTable.GetMessage("FrequencyWLSearch4") + Environment.NewLine;
// if (this.DisplayPercentages)
// strText += this.GraphemeInventory.SortedSyllographPercentagesInWordList();
// else strText += this.GraphemeInventory.SortedSyllographCountsInWordList();
// this.SearchResults = strText;
// this.SearchCount = wl.WordCount();
// return this;
//}
public FrequencyWLSearch ExecuteFrequencySearch(WordList wl)
{
Word wrd = null;
int nWord = 0;
string strText = "";
string str = "";
// Reset all words in word list to be initially available
for (int i = 0; i < wl.WordCount(); i++)
{
wrd = wl.GetWord(i);
wrd.Available = true;
}
// Filter out words for the count
for (int i = 0; i < wl.WordCount(); i++)
{
wrd = wl.GetWord(i);
if (this.SearchOptions != null)
{
if (!this.SearchOptions.MatchesWord(wrd))
wrd.Available = false;
else nWord++;
}
else if ((wrd.IsSightWord()) && (this.IgnoreSightWords))
wrd.Available = false;
else nWord++;
}
// Update Grapheme counts
m_GraphemeInventory = wl.UpdateGraphemeCounts(this.GraphemeInventory, this.IgnoreSightWords, this.IgnoreTone);
//strText += "Consonants" + Environment.NewLine;
str = m_Settings.LocalizationTable.GetMessage("FrequencyWLSearch1");
if (str == "")
str = "Consonants";
strText += str + Environment.NewLine;
if (this.DisplayPercentages)
strText += this.GraphemeInventory.SortedConsonantPercentagesInWordList();
else strText += this.GraphemeInventory.SortedConsonantCountsInWordList();
strText += Environment.NewLine;
//strText += "Vowels" + Environment.NewLine;
str = m_Settings.LocalizationTable.GetMessage("FrequencyWLSearch2");
if (str == "")
str = "Vowels";
strText += str + Environment.NewLine;
if (this.DisplayPercentages)
strText += this.GraphemeInventory.SortedVowelPercentagesInWordList();
else strText += this.GraphemeInventory.SortedVowelCountsInWordList();
strText += Environment.NewLine;
//strText += "Tones" + Environment.NewLine;
if (!this.IgnoreTone)
{
str = m_Settings.LocalizationTable.GetMessage("FrequencyWLSearch3");
if (str == "")
str = "Tones";
strText += str + Environment.NewLine;
if (this.DisplayPercentages)
strText += this.GraphemeInventory.SortedTonePercentsgesInWordList();
else strText += this.GraphemeInventory.SortedToneCountsInWordList();
strText += Environment.NewLine;
}
//strText += "Syllographs" + Environment.NewLine;
str = m_Settings.LocalizationTable.GetMessage("FrequencyWLSearch4");
if (str == "")
str = "Syllographs";
strText += str + Environment.NewLine;
if (this.DisplayPercentages)
strText += this.GraphemeInventory.SortedSyllographPercentagesInWordList();
else strText += this.GraphemeInventory.SortedSyllographCountsInWordList();
this.SearchResults = strText;
this.SearchCount = nWord;
return this;
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Media3D;
namespace SpatialAnalysis.Visualization3D
{
/// <summary>
/// Class FaceIndices.
/// Represents a face of a 3D mesh which is a triangle
/// </summary>
public class FaceIndices
{
/// <summary>
/// Gets or sets the indices.
/// </summary>
/// <value>The indices.</value>
public int[] Indices { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="FaceIndices"/> class.
/// </summary>
/// <param name="v1">The v1.</param>
/// <param name="v2">The v2.</param>
/// <param name="v3">The v3.</param>
public FaceIndices(int v1, int v2, int v3)
{
this.Indices = new int[] { v1, v2, v3 };
}
/// <summary>
/// Initializes a new instance of the <see cref="FaceIndices"/> class.
/// </summary>
public FaceIndices()
{
this.Indices = new int[3];
}
/// <summary>
/// Flips this instance and its normal
/// </summary>
public void Flip()
{
Array.Reverse(this.Indices);
}
/// <summary>
/// Copies this instance deeply.
/// </summary>
/// <returns>FaceIndices.</returns>
public FaceIndices Copy()
{
return new FaceIndices(this.Indices[0], this.Indices[1], this.Indices[2]);
}
}
/// <summary>
/// Class MeshIntersectionEdge.
/// </summary>
internal class MeshIntersectionEdge
{
/// <summary>
/// Gets or sets the start point of the intersecting line segment.
/// </summary>
/// <value>The start.</value>
public Point3D Start { get; set; }
/// <summary>
/// Gets or sets the end point of the intersecting line segment.
/// </summary>
/// <value>The end.</value>
public Point3D End { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MeshIntersectionEdge"/> class.
/// </summary>
/// <param name="start">The start point.</param>
/// <param name="end">The end point.</param>
public MeshIntersectionEdge(Point3D start, Point3D end)
{
this.Start = start;
this.End = end;
}
}
/// <summary>
/// Class Face. Represents a face of a mesh.
/// </summary>
internal class Face
{
/// <summary>
/// Gets or sets the vertices.
/// </summary>
/// <value>The vertices.</value>
public Point3D[] Vertices { get; set; }
/// <summary>
/// Gets or sets the vertex with maximum elevation.
/// </summary>
/// <value>The maximum.</value>
public double Max { get; set; }
/// <summary>
/// Gets or sets the vertex with minimum elevation.
/// </summary>
/// <value>The minimum.</value>
public double Min { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Face"/> class.
/// </summary>
/// <param name="p1">The p1.</param>
/// <param name="p2">The p2.</param>
/// <param name="p3">The p3.</param>
public Face(Point3D p1, Point3D p2, Point3D p3)
{
this.Vertices = new Point3D[] { p1, p2, p3 };
this.Max = Math.Max(p1.Z, Math.Max(p2.Z, p3.Z));
this.Min = Math.Min(p1.Z, Math.Min(p2.Z, p3.Z));
}
/// <summary>
/// Determines if a plane at the specified elevation intersects with this face.
/// </summary>
/// <param name="elevation">The elevation.</param>
/// <returns><c>true</c> if intersects, <c>false</c> otherwise.</returns>
public bool Intersects(double elevation)
{
return elevation >= this.Min && elevation <= this.Max;
}
private static bool IntersectionsWithLine(Point3D p1, Point3D p2, double elevation)
{
return (p1.Z - elevation) * (p2.Z - elevation) <= 0;
}
private static Point3D GetIntersectionPoint(Point3D p1, Point3D p2, double elevation)
{
double zDifference = p1.Z - p2.Z;
var direction = Point3D.Subtract(p2, p1);
double length = direction.Length;
//u/length= (p1.Z-elevation)/zDifference
double u = length * (p1.Z-elevation) / zDifference;
var normalizedDirection = Vector3D.Divide(direction, length);
Point3D intersection = p1 + u * normalizedDirection;
return intersection;
}
/// <summary>
/// Gets the intersection.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns>MeshIntersectionEdge.</returns>
public MeshIntersectionEdge GetIntersection(double offset)
{
List<Point3D> plus = new List<Point3D>();
List<Point3D> zero = new List<Point3D>();
List<Point3D> minus = new List<Point3D>();
for (int i = 0; i < 3; i++)
{
double z = this.Vertices[i].Z;
if (z > offset)
{
plus.Add(this.Vertices[i]);
}
else if (z == offset)
{
zero.Add(this.Vertices[i]);
}
else //if (z < offset)
{
minus.Add(this.Vertices[i]);
}
}
if (plus.Count == 3 || minus.Count == 3 || zero.Count == 3)
{
return null;
}
if (zero.Count == 1)
{
if ((plus.Count == 0 || minus.Count == 0))
{
return null;
}
else // there is a point on the top and a point on the bottom
{
return new MeshIntersectionEdge(zero[0], GetIntersectionPoint(plus[0], minus[0], offset));
}
}
if (zero.Count == 2)
{
return new MeshIntersectionEdge(zero[0], zero[1]);
}
// if (zero.Count == 0)
var pnts = new List<Point3D>(2);
foreach (Point3D item1 in plus)
{
foreach (Point3D item2 in minus)
{
pnts.Add(GetIntersectionPoint(item2, item1, offset));
}
}
return new MeshIntersectionEdge(pnts[0], pnts[1]);
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmRegister
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmRegister() : base()
{
Load += frmRegister_Load;
KeyPress += frmRegister_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
public System.Windows.Forms.TextBox txtCompany;
public System.Windows.Forms.Label _lbl_0;
public System.Windows.Forms.Label _lbl_1;
public System.Windows.Forms.Label _lbl_2;
public System.Windows.Forms.Label _lbl_3;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_1;
public System.Windows.Forms.Panel _picMode_0;
public System.Windows.Forms.TextBox txtKey;
public System.Windows.Forms.Label lblCompany;
public System.Windows.Forms.Label _Label2_2;
public System.Windows.Forms.Label _Label1_1;
public System.Windows.Forms.Label _Label2_0;
public System.Windows.Forms.Label lblCode;
public System.Windows.Forms.Label _Label2_1;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_3;
public System.Windows.Forms.Panel _picMode_1;
private System.Windows.Forms.Button withEventsField_cmdNext;
public System.Windows.Forms.Button cmdNext {
get { return withEventsField_cmdNext; }
set {
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click -= cmdNext_Click;
}
withEventsField_cmdNext = value;
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click += cmdNext_Click;
}
}
}
public System.Windows.Forms.Label Label4;
public System.Windows.Forms.Label Label3;
//Public WithEvents Label1 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents Label2 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents picMode As Microsoft.VisualBasic.Compatibility.VB6.PanelArray
public OvalShapeArray Shape1;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer2;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmRegister));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.ShapeContainer2 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this.cmdExit = new System.Windows.Forms.Button();
this._picMode_0 = new System.Windows.Forms.Panel();
this.txtCompany = new System.Windows.Forms.TextBox();
this._lbl_0 = new System.Windows.Forms.Label();
this._lbl_1 = new System.Windows.Forms.Label();
this._lbl_2 = new System.Windows.Forms.Label();
this._lbl_3 = new System.Windows.Forms.Label();
this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._Shape1_1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._picMode_1 = new System.Windows.Forms.Panel();
this.txtKey = new System.Windows.Forms.TextBox();
this.lblCompany = new System.Windows.Forms.Label();
this._Label2_2 = new System.Windows.Forms.Label();
this._Label1_1 = new System.Windows.Forms.Label();
this._Label2_0 = new System.Windows.Forms.Label();
this.lblCode = new System.Windows.Forms.Label();
this._Label2_1 = new System.Windows.Forms.Label();
this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._Shape1_3 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this.cmdNext = new System.Windows.Forms.Button();
this.Label4 = new System.Windows.Forms.Label();
this.Label3 = new System.Windows.Forms.Label();
//Me.Label1 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.Label2 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.picMode = New Microsoft.VisualBasic.Compatibility.VB6.PanelArray(components)
this.Shape1 = new OvalShapeArray(components);
this._picMode_0.SuspendLayout();
this._picMode_1.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.Label1, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.Label2, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.picMode, System.ComponentModel.ISupportInitialize).BeginInit()
((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit();
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Registration Wizard";
this.ClientSize = new System.Drawing.Size(296, 282);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmRegister";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Size = new System.Drawing.Size(97, 28);
this.cmdExit.Location = new System.Drawing.Point(8, 249);
this.cmdExit.TabIndex = 8;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.TabStop = true;
this.cmdExit.Name = "cmdExit";
this._picMode_0.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._picMode_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._picMode_0.Size = new System.Drawing.Size(283, 232);
this._picMode_0.Location = new System.Drawing.Point(6, 9);
this._picMode_0.TabIndex = 13;
this._picMode_0.TabStop = false;
this._picMode_0.Dock = System.Windows.Forms.DockStyle.None;
this._picMode_0.CausesValidation = true;
this._picMode_0.Enabled = true;
this._picMode_0.Cursor = System.Windows.Forms.Cursors.Default;
this._picMode_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._picMode_0.Visible = true;
this._picMode_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._picMode_0.Name = "_picMode_0";
this.txtCompany.AutoSize = false;
this.txtCompany.Size = new System.Drawing.Size(271, 19);
this.txtCompany.Location = new System.Drawing.Point(6, 201);
this.txtCompany.MaxLength = 50;
this.txtCompany.TabIndex = 6;
this.txtCompany.AcceptsReturn = true;
this.txtCompany.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtCompany.BackColor = System.Drawing.SystemColors.Window;
this.txtCompany.CausesValidation = true;
this.txtCompany.Enabled = true;
this.txtCompany.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtCompany.HideSelection = true;
this.txtCompany.ReadOnly = false;
this.txtCompany.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtCompany.Multiline = false;
this.txtCompany.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtCompany.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtCompany.TabStop = true;
this.txtCompany.Visible = true;
this.txtCompany.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtCompany.Name = "txtCompany";
this._lbl_0.Text = "Store Name:";
this._lbl_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lbl_0.Size = new System.Drawing.Size(178, 16);
this._lbl_0.Location = new System.Drawing.Point(6, 186);
this._lbl_0.TabIndex = 5;
this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Enabled = true;
this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.UseMnemonic = true;
this._lbl_0.Visible = true;
this._lbl_0.AutoSize = false;
this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_0.Name = "_lbl_0";
this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._lbl_1.Text = "Welcome to the 4POS Application Suite of products designed for the Retailer.";
this._lbl_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lbl_1.Size = new System.Drawing.Size(280, 43);
this._lbl_1.Location = new System.Drawing.Point(0, 0);
this._lbl_1.TabIndex = 2;
this._lbl_1.BackColor = System.Drawing.Color.Transparent;
this._lbl_1.Enabled = true;
this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_1.UseMnemonic = true;
this._lbl_1.Visible = true;
this._lbl_1.AutoSize = false;
this._lbl_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_1.Name = "_lbl_1";
this._lbl_2.Text = "In the text box below, please capture your store's name. It is imperative that you capture you stores name correctly as this makes up part of your licensing agreement with 4POS.";
this._lbl_2.Size = new System.Drawing.Size(274, 64);
this._lbl_2.Location = new System.Drawing.Point(6, 36);
this._lbl_2.TabIndex = 3;
this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Enabled = true;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.UseMnemonic = true;
this._lbl_2.Visible = true;
this._lbl_2.AutoSize = false;
this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_2.Name = "_lbl_2";
this._lbl_3.Text = "To bypass this registration process, press the \"Exit\" button. This will activate the demo version of this software, which is fully functional except that you may only complete ten \"Day End\" runs.";
this._lbl_3.Size = new System.Drawing.Size(274, 64);
this._lbl_3.Location = new System.Drawing.Point(6, 99);
this._lbl_3.TabIndex = 4;
this._lbl_3.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_3.BackColor = System.Drawing.Color.Transparent;
this._lbl_3.Enabled = true;
this._lbl_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_3.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_3.UseMnemonic = true;
this._lbl_3.Visible = true;
this._lbl_3.AutoSize = false;
this._lbl_3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_3.Name = "_lbl_3";
this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_0.Size = new System.Drawing.Size(283, 133);
this._Shape1_0.Location = new System.Drawing.Point(0, 30);
this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_0.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_0.BorderWidth = 1;
this._Shape1_0.FillColor = System.Drawing.Color.Black;
this._Shape1_0.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_0.Visible = true;
this._Shape1_0.Name = "_Shape1_0";
this._Shape1_1.BackColor = System.Drawing.Color.FromArgb(255, 192, 192);
this._Shape1_1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_1.Size = new System.Drawing.Size(283, 46);
this._Shape1_1.Location = new System.Drawing.Point(0, 183);
this._Shape1_1.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_1.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_1.BorderWidth = 1;
this._Shape1_1.FillColor = System.Drawing.Color.Black;
this._Shape1_1.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_1.Visible = true;
this._Shape1_1.Name = "_Shape1_1";
this._picMode_1.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this._picMode_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._picMode_1.Size = new System.Drawing.Size(283, 232);
this._picMode_1.Location = new System.Drawing.Point(333, 57);
this._picMode_1.TabIndex = 9;
this._picMode_1.TabStop = false;
this._picMode_1.Visible = false;
this._picMode_1.Dock = System.Windows.Forms.DockStyle.None;
this._picMode_1.CausesValidation = true;
this._picMode_1.Enabled = true;
this._picMode_1.Cursor = System.Windows.Forms.Cursors.Default;
this._picMode_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._picMode_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._picMode_1.Name = "_picMode_1";
this.txtKey.AutoSize = false;
this.txtKey.Size = new System.Drawing.Size(175, 19);
this.txtKey.Location = new System.Drawing.Point(99, 186);
this.txtKey.TabIndex = 1;
this.txtKey.AcceptsReturn = true;
this.txtKey.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtKey.BackColor = System.Drawing.SystemColors.Window;
this.txtKey.CausesValidation = true;
this.txtKey.Enabled = true;
this.txtKey.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtKey.HideSelection = true;
this.txtKey.ReadOnly = false;
this.txtKey.MaxLength = 0;
this.txtKey.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtKey.Multiline = false;
this.txtKey.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtKey.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtKey.TabStop = true;
this.txtKey.Visible = true;
this.txtKey.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtKey.Name = "txtKey";
this.lblCompany.BackColor = System.Drawing.Color.Transparent;
this.lblCompany.Text = "123456789012345";
this.lblCompany.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblCompany.ForeColor = System.Drawing.SystemColors.WindowText;
this.lblCompany.Size = new System.Drawing.Size(276, 18);
this.lblCompany.Location = new System.Drawing.Point(3, 87);
this.lblCompany.TabIndex = 15;
this.lblCompany.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblCompany.Enabled = true;
this.lblCompany.Cursor = System.Windows.Forms.Cursors.Default;
this.lblCompany.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblCompany.UseMnemonic = true;
this.lblCompany.Visible = true;
this.lblCompany.AutoSize = false;
this.lblCompany.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblCompany.Name = "lblCompany";
this._Label2_2.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._Label2_2.Text = "Company Name:";
this._Label2_2.Size = new System.Drawing.Size(93, 13);
this._Label2_2.Location = new System.Drawing.Point(-12, 75);
this._Label2_2.TabIndex = 14;
this._Label2_2.BackColor = System.Drawing.Color.Transparent;
this._Label2_2.Enabled = true;
this._Label2_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label2_2.Cursor = System.Windows.Forms.Cursors.Default;
this._Label2_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label2_2.UseMnemonic = true;
this._Label2_2.Visible = true;
this._Label2_2.AutoSize = false;
this._Label2_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label2_2.Name = "_Label2_2";
this._Label1_1.Text = "Please contact a \"4POS\" representative and quote the company name and registration code below to get your new activation key for the product.";
this._Label1_1.Size = new System.Drawing.Size(280, 58);
this._Label1_1.Location = new System.Drawing.Point(3, 0);
this._Label1_1.TabIndex = 12;
this._Label1_1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._Label1_1.BackColor = System.Drawing.Color.Transparent;
this._Label1_1.Enabled = true;
this._Label1_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label1_1.Cursor = System.Windows.Forms.Cursors.Default;
this._Label1_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label1_1.UseMnemonic = true;
this._Label1_1.Visible = true;
this._Label1_1.AutoSize = false;
this._Label1_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label1_1.Name = "_Label1_1";
this._Label2_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._Label2_0.Text = "Registration code:";
this._Label2_0.Size = new System.Drawing.Size(93, 13);
this._Label2_0.Location = new System.Drawing.Point(-3, 102);
this._Label2_0.TabIndex = 11;
this._Label2_0.BackColor = System.Drawing.Color.Transparent;
this._Label2_0.Enabled = true;
this._Label2_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label2_0.Cursor = System.Windows.Forms.Cursors.Default;
this._Label2_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label2_0.UseMnemonic = true;
this._Label2_0.Visible = true;
this._Label2_0.AutoSize = false;
this._Label2_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label2_0.Name = "_Label2_0";
this.lblCode.BackColor = System.Drawing.Color.Transparent;
this.lblCode.Text = "123456789012345";
this.lblCode.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblCode.ForeColor = System.Drawing.SystemColors.WindowText;
this.lblCode.Size = new System.Drawing.Size(123, 18);
this.lblCode.Location = new System.Drawing.Point(3, 114);
this.lblCode.TabIndex = 10;
this.lblCode.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblCode.Enabled = true;
this.lblCode.Cursor = System.Windows.Forms.Cursors.Default;
this.lblCode.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblCode.UseMnemonic = true;
this.lblCode.Visible = true;
this.lblCode.AutoSize = false;
this.lblCode.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblCode.Name = "lblCode";
this._Label2_1.Text = "Activation key:";
this._Label2_1.Size = new System.Drawing.Size(70, 13);
this._Label2_1.Location = new System.Drawing.Point(21, 189);
this._Label2_1.TabIndex = 0;
this._Label2_1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._Label2_1.BackColor = System.Drawing.Color.Transparent;
this._Label2_1.Enabled = true;
this._Label2_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Label2_1.Cursor = System.Windows.Forms.Cursors.Default;
this._Label2_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Label2_1.UseMnemonic = true;
this._Label2_1.Visible = true;
this._Label2_1.AutoSize = true;
this._Label2_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._Label2_1.Name = "_Label2_1";
this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_2.Size = new System.Drawing.Size(283, 67);
this._Shape1_2.Location = new System.Drawing.Point(0, 72);
this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_2.BorderWidth = 1;
this._Shape1_2.FillColor = System.Drawing.Color.Black;
this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_2.Visible = true;
this._Shape1_2.Name = "_Shape1_2";
this._Shape1_3.BackColor = System.Drawing.Color.FromArgb(255, 192, 192);
this._Shape1_3.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_3.Size = new System.Drawing.Size(283, 31);
this._Shape1_3.Location = new System.Drawing.Point(0, 180);
this._Shape1_3.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_3.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_3.BorderWidth = 1;
this._Shape1_3.FillColor = System.Drawing.Color.Black;
this._Shape1_3.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_3.Visible = true;
this._Shape1_3.Name = "_Shape1_3";
this.cmdNext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdNext.Text = "&Next";
this.cmdNext.Size = new System.Drawing.Size(97, 28);
this.cmdNext.Location = new System.Drawing.Point(186, 249);
this.cmdNext.TabIndex = 7;
this.cmdNext.BackColor = System.Drawing.SystemColors.Control;
this.cmdNext.CausesValidation = true;
this.cmdNext.Enabled = true;
this.cmdNext.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNext.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNext.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNext.TabStop = true;
this.cmdNext.Name = "cmdNext";
this.Label4.Text = "Label4";
this.Label4.Size = new System.Drawing.Size(273, 33);
this.Label4.Location = new System.Drawing.Point(16, 320);
this.Label4.TabIndex = 17;
this.Label4.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label4.BackColor = System.Drawing.SystemColors.Control;
this.Label4.Enabled = true;
this.Label4.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label4.Cursor = System.Windows.Forms.Cursors.Default;
this.Label4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label4.UseMnemonic = true;
this.Label4.Visible = true;
this.Label4.AutoSize = false;
this.Label4.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label4.Name = "Label4";
this.Label3.Text = "Label3";
this.Label3.Size = new System.Drawing.Size(265, 25);
this.Label3.Location = new System.Drawing.Point(16, 288);
this.Label3.TabIndex = 16;
this.Label3.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label3.BackColor = System.Drawing.SystemColors.Control;
this.Label3.Enabled = true;
this.Label3.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label3.Cursor = System.Windows.Forms.Cursors.Default;
this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label3.UseMnemonic = true;
this.Label3.Visible = true;
this.Label3.AutoSize = false;
this.Label3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label3.Name = "Label3";
this.Controls.Add(cmdExit);
this.Controls.Add(_picMode_0);
this.Controls.Add(_picMode_1);
this.Controls.Add(cmdNext);
this.Controls.Add(Label4);
this.Controls.Add(Label3);
this._picMode_0.Controls.Add(txtCompany);
this._picMode_0.Controls.Add(_lbl_0);
this._picMode_0.Controls.Add(_lbl_1);
this._picMode_0.Controls.Add(_lbl_2);
this._picMode_0.Controls.Add(_lbl_3);
this.ShapeContainer1.Shapes.Add(_Shape1_0);
this.ShapeContainer1.Shapes.Add(_Shape1_1);
this._picMode_0.Controls.Add(ShapeContainer1);
this._picMode_1.Controls.Add(txtKey);
this._picMode_1.Controls.Add(lblCompany);
this._picMode_1.Controls.Add(_Label2_2);
this._picMode_1.Controls.Add(_Label1_1);
this._picMode_1.Controls.Add(_Label2_0);
this._picMode_1.Controls.Add(lblCode);
this._picMode_1.Controls.Add(_Label2_1);
this.ShapeContainer2.Shapes.Add(_Shape1_2);
this.ShapeContainer2.Shapes.Add(_Shape1_3);
this._picMode_1.Controls.Add(ShapeContainer2);
//Me.Label1.SetIndex(_Label1_1, CType(1, Short))
//Me.Label2.SetIndex(_Label2_2, CType(2, Short))
//Me.Label2.SetIndex(_Label2_0, CType(0, Short))
//Me.Label2.SetIndex(_Label2_1, CType(1, Short))
//Me.lbl.SetIndex(_lbl_0, CType(0, Short))
//Me.lbl.SetIndex(_lbl_1, CType(1, Short))
//Me.lbl.SetIndex(_lbl_2, CType(2, Short))
//Me.lbl.SetIndex(_lbl_3, CType(3, Short))
//Me.picMode.SetIndex(_picMode_0, CType(0, Short))
//Me.picMode.SetIndex(_picMode_1, CType(1, Short))
//Me.Shape1.SetIndex(_Shape1_0, CType(0, Short))
//Me.Shape1.SetIndex(_Shape1_1, CType(1, Short))
//Me.Shape1.SetIndex(_Shape1_2, CType(2, Short))
//Me.Shape1.SetIndex(_Shape1_3, CType(3, Short))
((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit();
//CType(Me.picMode, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.Label2, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.Label1, System.ComponentModel.ISupportInitialize).EndInit()
this._picMode_0.ResumeLayout(false);
this._picMode_1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Management.StreamAnalytics;
using Microsoft.Azure.Management.StreamAnalytics.Models;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace StreamAnalytics.Tests
{
public class InputTests : TestBase
{
[Fact(Skip = "ReRecord due to CR change")]
public async Task InputOperationsTest_Stream_Blob()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string resourceGroupName = TestUtilities.GenerateName("sjrg");
string jobName = TestUtilities.GenerateName("sj");
string inputName = TestUtilities.GenerateName("input");
var resourceManagementClient = this.GetResourceManagementClient(context);
var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context);
string expectedInputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.InputsResourceType);
string expectedInputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.InputsResourceType, inputName);
resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation });
StorageAccount storageAccount = new StorageAccount()
{
AccountName = TestHelper.AccountName,
AccountKey = TestHelper.AccountKey
};
Input input = new Input()
{
Properties = new StreamInputProperties()
{
Serialization = new CsvSerialization()
{
FieldDelimiter = ",",
Encoding = Encoding.UTF8
},
Datasource = new BlobStreamInputDataSource()
{
StorageAccounts = new[] { storageAccount },
Container = TestHelper.Container,
PathPattern = "{date}/{time}",
DateFormat = "yyyy/MM/dd",
TimeFormat = "HH",
SourcePartitionCount = 16
}
}
};
// PUT job
streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName);
// PUT input
var putResponse = await streamAnalyticsManagementClient.Inputs.CreateOrReplaceWithHttpMessagesAsync(input, resourceGroupName, jobName, inputName);
storageAccount.AccountKey = null; // Null out because secrets are not returned in responses
ValidationHelper.ValidateInput(input, putResponse.Body, false);
Assert.Equal(expectedInputResourceId, putResponse.Body.Id);
Assert.Equal(inputName, putResponse.Body.Name);
Assert.Equal(expectedInputType, putResponse.Body.Type);
// Verify GET request returns expected input
var getResponse = await streamAnalyticsManagementClient.Inputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, getResponse.Body, true);
// ETag should be the same
Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag);
// Test Input
var testResult = streamAnalyticsManagementClient.Inputs.Test(resourceGroupName, jobName, inputName);
Assert.Equal("TestSucceeded", testResult.Status);
Assert.Null(testResult.Error);
// PATCH input
var inputPatch = new Input()
{
Properties = new StreamInputProperties()
{
Serialization = new CsvSerialization()
{
FieldDelimiter = "|",
Encoding = Encoding.UTF8
},
Datasource = new BlobStreamInputDataSource()
{
SourcePartitionCount = 32
}
}
};
((CsvSerialization)putResponse.Body.Properties.Serialization).FieldDelimiter = ((CsvSerialization)inputPatch.Properties.Serialization).FieldDelimiter;
((BlobStreamInputDataSource)((StreamInputProperties)putResponse.Body.Properties).Datasource).SourcePartitionCount = ((BlobStreamInputDataSource)((StreamInputProperties)inputPatch.Properties).Datasource).SourcePartitionCount;
var patchResponse = await streamAnalyticsManagementClient.Inputs.UpdateWithHttpMessagesAsync(inputPatch, resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, patchResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag);
// Run another GET input to verify that it returns the newly updated properties as well
getResponse = await streamAnalyticsManagementClient.Inputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, getResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag);
Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag);
// List input and verify that the input shows up in the list
var listResult = streamAnalyticsManagementClient.Inputs.ListByStreamingJob(resourceGroupName, jobName);
Assert.Single(listResult);
ValidationHelper.ValidateInput(putResponse.Body, listResult.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listResult.Single().Properties.Etag);
// Get job with input expanded and verify that the input shows up
var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "inputs");
Assert.Single(getJobResponse.Inputs);
ValidationHelper.ValidateInput(putResponse.Body, getJobResponse.Inputs.Single(), true);
Assert.Equal(getResponse.Headers.ETag, getJobResponse.Inputs.Single().Properties.Etag);
// Delete input
streamAnalyticsManagementClient.Inputs.Delete(resourceGroupName, jobName, inputName);
// Verify that list operation returns an empty list after deleting the input
listResult = streamAnalyticsManagementClient.Inputs.ListByStreamingJob(resourceGroupName, jobName);
Assert.Empty(listResult);
// Get job with input expanded and verify that there are no inputs after deleting the input
getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "inputs");
Assert.Empty(getJobResponse.Inputs);
}
}
[Fact(Skip = "ReRecord due to CR change")]
public async Task InputOperationsTest_Stream_EventHub()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string resourceGroupName = TestUtilities.GenerateName("sjrg");
string jobName = TestUtilities.GenerateName("sj");
string inputName = TestUtilities.GenerateName("input");
var resourceManagementClient = this.GetResourceManagementClient(context);
var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context);
string expectedInputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.InputsResourceType);
string expectedInputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.InputsResourceType, inputName);
resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation });
EventHubStreamInputDataSource eventHub = new EventHubStreamInputDataSource()
{
ServiceBusNamespace = TestHelper.ServiceBusNamespace,
SharedAccessPolicyName = TestHelper.SharedAccessPolicyName,
SharedAccessPolicyKey = TestHelper.SharedAccessPolicyKey,
EventHubName = TestHelper.EventHubName,
ConsumerGroupName = "sdkconsumergroup"
};
Input input = new Input()
{
Properties = new StreamInputProperties()
{
Serialization = new JsonSerialization()
{
Encoding = Encoding.UTF8
},
Datasource = eventHub
}
};
// PUT job
streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName);
// PUT input
var putResponse = await streamAnalyticsManagementClient.Inputs.CreateOrReplaceWithHttpMessagesAsync(input, resourceGroupName, jobName, inputName);
eventHub.SharedAccessPolicyKey = null; // Null out because secrets are not returned in responses
ValidationHelper.ValidateInput(input, putResponse.Body, false);
Assert.Equal(expectedInputResourceId, putResponse.Body.Id);
Assert.Equal(inputName, putResponse.Body.Name);
Assert.Equal(expectedInputType, putResponse.Body.Type);
// Verify GET request returns expected input
var getResponse = await streamAnalyticsManagementClient.Inputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, getResponse.Body, true);
// ETag should be the same
Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag);
// Test Input
var testResult = streamAnalyticsManagementClient.Inputs.Test(resourceGroupName, jobName, inputName);
Assert.Equal("TestSucceeded", testResult.Status);
Assert.Null(testResult.Error);
// PATCH input
var inputPatch = new Input()
{
Properties = new StreamInputProperties()
{
Serialization = new AvroSerialization(),
Datasource = new EventHubStreamInputDataSource()
{
ConsumerGroupName = "differentConsumerGroupName"
}
}
};
putResponse.Body.Properties.Serialization = inputPatch.Properties.Serialization;
((EventHubStreamInputDataSource)((StreamInputProperties)putResponse.Body.Properties).Datasource).ConsumerGroupName = ((EventHubStreamInputDataSource)((StreamInputProperties)inputPatch.Properties).Datasource).ConsumerGroupName;
var patchResponse = await streamAnalyticsManagementClient.Inputs.UpdateWithHttpMessagesAsync(inputPatch, resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, patchResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag);
// Run another GET input to verify that it returns the newly updated properties as well
getResponse = await streamAnalyticsManagementClient.Inputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, getResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag);
Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag);
// List input and verify that the input shows up in the list
var listResult = streamAnalyticsManagementClient.Inputs.ListByStreamingJob(resourceGroupName, jobName);
Assert.Single(listResult);
ValidationHelper.ValidateInput(putResponse.Body, listResult.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listResult.Single().Properties.Etag);
// Get job with input expanded and verify that the input shows up
var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "inputs");
Assert.Single(getJobResponse.Inputs);
ValidationHelper.ValidateInput(putResponse.Body, getJobResponse.Inputs.Single(), true);
Assert.Equal(getResponse.Headers.ETag, getJobResponse.Inputs.Single().Properties.Etag);
// Delete input
streamAnalyticsManagementClient.Inputs.Delete(resourceGroupName, jobName, inputName);
// Verify that list operation returns an empty list after deleting the input
listResult = streamAnalyticsManagementClient.Inputs.ListByStreamingJob(resourceGroupName, jobName);
Assert.Empty(listResult);
// Get job with input expanded and verify that there are no inputs after deleting the input
getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "inputs");
Assert.Empty(getJobResponse.Inputs);
}
}
[Fact(Skip = "ReRecord due to CR change")]
public async Task InputOperationsTest_Stream_IoTHub()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string resourceGroupName = TestUtilities.GenerateName("sjrg");
string jobName = TestUtilities.GenerateName("sj");
string inputName = TestUtilities.GenerateName("input");
var resourceManagementClient = this.GetResourceManagementClient(context);
var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context);
string expectedInputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.InputsResourceType);
string expectedInputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.InputsResourceType, inputName);
resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation });
IoTHubStreamInputDataSource iotHub = new IoTHubStreamInputDataSource()
{
IotHubNamespace = TestHelper.IoTHubNamespace,
SharedAccessPolicyName = TestHelper.IoTSharedAccessPolicyName,
SharedAccessPolicyKey = TestHelper.IoTHubSharedAccessPolicyKey,
Endpoint = "messages/events",
ConsumerGroupName = "sdkconsumergroup"
};
Input input = new Input()
{
Properties = new StreamInputProperties()
{
Serialization = new AvroSerialization(),
Datasource = iotHub
}
};
// PUT job
streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName);
// PUT input
var putResponse = await streamAnalyticsManagementClient.Inputs.CreateOrReplaceWithHttpMessagesAsync(input, resourceGroupName, jobName, inputName);
iotHub.SharedAccessPolicyKey = null; // Null out because secrets are not returned in responses
ValidationHelper.ValidateInput(input, putResponse.Body, false);
Assert.Equal(expectedInputResourceId, putResponse.Body.Id);
Assert.Equal(inputName, putResponse.Body.Name);
Assert.Equal(expectedInputType, putResponse.Body.Type);
// Verify GET request returns expected input
var getResponse = await streamAnalyticsManagementClient.Inputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, getResponse.Body, true);
// ETag should be the same
Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag);
// Test Input
var testResult = streamAnalyticsManagementClient.Inputs.Test(resourceGroupName, jobName, inputName);
Assert.Equal("TestSucceeded", testResult.Status);
Assert.Null(testResult.Error);
// PATCH input
var inputPatch = new Input()
{
Properties = new StreamInputProperties()
{
Serialization = new CsvSerialization()
{
FieldDelimiter = "|",
Encoding = Encoding.UTF8
},
Datasource = new IoTHubStreamInputDataSource()
{
Endpoint = "messages/operationsMonitoringEvents"
}
}
};
putResponse.Body.Properties.Serialization = inputPatch.Properties.Serialization;
((IoTHubStreamInputDataSource)((StreamInputProperties)putResponse.Body.Properties).Datasource).Endpoint = ((IoTHubStreamInputDataSource)((StreamInputProperties)inputPatch.Properties).Datasource).Endpoint;
var patchResponse = await streamAnalyticsManagementClient.Inputs.UpdateWithHttpMessagesAsync(inputPatch, resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, patchResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag);
// Run another GET input to verify that it returns the newly updated properties as well
getResponse = await streamAnalyticsManagementClient.Inputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, getResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag);
Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag);
// List input and verify that the input shows up in the list
var listResult = streamAnalyticsManagementClient.Inputs.ListByStreamingJob(resourceGroupName, jobName);
Assert.Single(listResult);
ValidationHelper.ValidateInput(putResponse.Body, listResult.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listResult.Single().Properties.Etag);
// Get job with input expanded and verify that the input shows up
var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "inputs");
Assert.Single(getJobResponse.Inputs);
ValidationHelper.ValidateInput(putResponse.Body, getJobResponse.Inputs.Single(), true);
Assert.Equal(getResponse.Headers.ETag, getJobResponse.Inputs.Single().Properties.Etag);
// Delete input
streamAnalyticsManagementClient.Inputs.Delete(resourceGroupName, jobName, inputName);
// Verify that list operation returns an empty list after deleting the input
listResult = streamAnalyticsManagementClient.Inputs.ListByStreamingJob(resourceGroupName, jobName);
Assert.Empty(listResult);
// Get job with input expanded and verify that there are no inputs after deleting the input
getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "inputs");
Assert.Empty(getJobResponse.Inputs);
}
}
[Fact(Skip = "ReRecord due to CR change")]
public async Task InputOperationsTest_Reference_Blob()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string resourceGroupName = TestUtilities.GenerateName("sjrg");
string jobName = TestUtilities.GenerateName("sj");
string inputName = TestUtilities.GenerateName("input");
var resourceManagementClient = this.GetResourceManagementClient(context);
var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context);
string expectedInputType = TestHelper.GetFullRestOnlyResourceType(TestHelper.InputsResourceType);
string expectedInputResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.InputsResourceType, inputName);
resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation });
StorageAccount storageAccount = new StorageAccount()
{
AccountName = TestHelper.AccountName,
AccountKey = TestHelper.AccountKey
};
Input input = new Input()
{
Properties = new ReferenceInputProperties()
{
Serialization = new CsvSerialization()
{
FieldDelimiter = ",",
Encoding = Encoding.UTF8
},
Datasource = new BlobReferenceInputDataSource()
{
StorageAccounts = new[] { storageAccount },
Container = TestHelper.Container,
PathPattern = "{date}/{time}",
DateFormat = "yyyy/MM/dd",
TimeFormat = "HH"
}
}
};
// PUT job
streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName);
// PUT input
var putResponse = await streamAnalyticsManagementClient.Inputs.CreateOrReplaceWithHttpMessagesAsync(input, resourceGroupName, jobName, inputName);
storageAccount.AccountKey = null; // Null out because secrets are not returned in responses
ValidationHelper.ValidateInput(input, putResponse.Body, false);
Assert.Equal(expectedInputResourceId, putResponse.Body.Id);
Assert.Equal(inputName, putResponse.Body.Name);
Assert.Equal(expectedInputType, putResponse.Body.Type);
// Verify GET request returns expected input
var getResponse = await streamAnalyticsManagementClient.Inputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, getResponse.Body, true);
// ETag should be the same
Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag);
// Test Input
var testResult = streamAnalyticsManagementClient.Inputs.Test(resourceGroupName, jobName, inputName);
Assert.Equal("TestSucceeded", testResult.Status);
Assert.Null(testResult.Error);
// PATCH input
var inputPatch = new Input()
{
Properties = new ReferenceInputProperties()
{
Serialization = new CsvSerialization()
{
FieldDelimiter = "|",
Encoding = Encoding.UTF8
},
Datasource = new BlobReferenceInputDataSource()
{
Container = "differentContainer"
}
}
};
((CsvSerialization)putResponse.Body.Properties.Serialization).FieldDelimiter = ((CsvSerialization)inputPatch.Properties.Serialization).FieldDelimiter;
((BlobReferenceInputDataSource)((ReferenceInputProperties)putResponse.Body.Properties).Datasource).Container = ((BlobReferenceInputDataSource)((ReferenceInputProperties)inputPatch.Properties).Datasource).Container;
var patchResponse = await streamAnalyticsManagementClient.Inputs.UpdateWithHttpMessagesAsync(inputPatch, resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, patchResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag);
// Run another GET input to verify that it returns the newly updated properties as well
getResponse = await streamAnalyticsManagementClient.Inputs.GetWithHttpMessagesAsync(resourceGroupName, jobName, inputName);
ValidationHelper.ValidateInput(putResponse.Body, getResponse.Body, true);
// ETag should be different after a PATCH operation
Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag);
Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag);
// List input and verify that the input shows up in the list
var listResult = streamAnalyticsManagementClient.Inputs.ListByStreamingJob(resourceGroupName, jobName);
Assert.Single(listResult);
ValidationHelper.ValidateInput(putResponse.Body, listResult.Single(), true);
Assert.Equal(getResponse.Headers.ETag, listResult.Single().Properties.Etag);
// Get job with input expanded and verify that the input shows up
var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "inputs");
Assert.Single(getJobResponse.Inputs);
ValidationHelper.ValidateInput(putResponse.Body, getJobResponse.Inputs.Single(), true);
Assert.Equal(getResponse.Headers.ETag, getJobResponse.Inputs.Single().Properties.Etag);
// Delete input
streamAnalyticsManagementClient.Inputs.Delete(resourceGroupName, jobName, inputName);
// Verify that list operation returns an empty list after deleting the input
listResult = streamAnalyticsManagementClient.Inputs.ListByStreamingJob(resourceGroupName, jobName);
Assert.Empty(listResult);
// Get job with input expanded and verify that there are no inputs after deleting the input
getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "inputs");
Assert.Empty(getJobResponse.Inputs);
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Hosting;
using Orleans.Runtime;
using Orleans.Streams;
using Orleans.TestingHost;
using Tester;
using TestExtensions;
using Xunit;
namespace UnitTests.StreamingTests
{
public class PubSubRendezvousGrainTests : OrleansTestingBase, IClassFixture<PubSubRendezvousGrainTests.Fixture>
{
private readonly Fixture fixture;
public class Fixture : BaseTestClusterFixture
{
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.AddSiloBuilderConfigurator<SiloHostConfigurator>();
}
public class SiloHostConfigurator : ISiloConfigurator
{
public void Configure(ISiloBuilder hostBuilder)
{
hostBuilder.AddFaultInjectionMemoryStorage("PubSubStore");
}
}
}
public PubSubRendezvousGrainTests(Fixture fixture)
{
this.fixture = fixture;
}
[Fact, TestCategory("BVT"), TestCategory("Streaming"), TestCategory("PubSub")]
public async Task RegisterConsumerFaultTest()
{
this.fixture.Logger.Info("************************ RegisterConsumerFaultTest *********************************");
var streamId = new InternalStreamId("ProviderName", StreamId.Create("StreamNamespace", Guid.NewGuid()));
var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>(streamId.ToString());
var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName);
// clean call, to make sure everything is happy and pubsub has state.
await pubSubGrain.RegisterConsumer(GuidId.GetGuidId(Guid.NewGuid()), streamId, null);
int consumers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(1, consumers);
// inject fault
await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when registering a new consumer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.RegisterConsumer(GuidId.GetGuidId(Guid.NewGuid()), streamId, null));
// pubsub grain should recover and still function
await pubSubGrain.RegisterConsumer(GuidId.GetGuidId(Guid.NewGuid()), streamId, null);
consumers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(2, consumers);
}
[Fact, TestCategory("BVT"), TestCategory("Streaming"), TestCategory("PubSub")]
public async Task UnregisterConsumerFaultTest()
{
this.fixture.Logger.Info("************************ UnregisterConsumerFaultTest *********************************");
var streamId = new InternalStreamId("ProviderName", StreamId.Create("StreamNamespace", Guid.NewGuid()));
var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>(streamId.ToString());
var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName);
// Add two consumers so when we remove the first it does a storage write, not a storage clear.
GuidId subscriptionId1 = GuidId.GetGuidId(Guid.NewGuid());
GuidId subscriptionId2 = GuidId.GetGuidId(Guid.NewGuid());
await pubSubGrain.RegisterConsumer(subscriptionId1, streamId, null);
await pubSubGrain.RegisterConsumer(subscriptionId2, streamId, null);
int consumers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(2, consumers);
// inject fault
await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when unregistering a consumer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.UnregisterConsumer(subscriptionId1, streamId));
// pubsub grain should recover and still function
await pubSubGrain.UnregisterConsumer(subscriptionId1, streamId);
consumers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(1, consumers);
// inject clear fault, because removing last consumer should trigger a clear storage call.
await faultGrain.AddFaultOnClear(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when unregistering a consumer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.UnregisterConsumer(subscriptionId2, streamId));
// pubsub grain should recover and still function
await pubSubGrain.UnregisterConsumer(subscriptionId2, streamId);
consumers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(0, consumers);
}
/// <summary>
/// This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension in the producer management calls.
/// TODO: Fix rendezvous implementation.
/// </summary>
/// <returns></returns>
[Fact(Skip = "This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension"), TestCategory("BVT"), TestCategory("Streaming"), TestCategory("PubSub")]
public async Task RegisterProducerFaultTest()
{
this.fixture.Logger.Info("************************ RegisterProducerFaultTest *********************************");
var streamId = new InternalStreamId("ProviderName", StreamId.Create("StreamNamespace", Guid.NewGuid()));
var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>(streamId.ToString());
var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName);
// clean call, to make sure everything is happy and pubsub has state.
await pubSubGrain.RegisterProducer(streamId, null);
int producers = await pubSubGrain.ProducerCount(streamId);
Assert.Equal(1, producers);
// inject fault
await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when registering a new producer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.RegisterProducer(streamId, null));
// pubsub grain should recover and still function
await pubSubGrain.RegisterProducer(streamId, null);
producers = await pubSubGrain.ProducerCount(streamId);
Assert.Equal(2, producers);
}
/// <summary>
/// This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension in the producer management calls.
/// TODO: Fix rendezvous implementation.
/// </summary>
[Fact(Skip = "This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension"), TestCategory("BVT"), TestCategory("Streaming"), TestCategory("PubSub")]
public async Task UnregisterProducerFaultTest()
{
this.fixture.Logger.Info("************************ UnregisterProducerFaultTest *********************************");
var streamId = new InternalStreamId("ProviderName", StreamId.Create("StreamNamespace", Guid.NewGuid()));
var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>(streamId.ToString());
var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName);
IStreamProducerExtension firstProducer = new DummyStreamProducerExtension();
IStreamProducerExtension secondProducer = new DummyStreamProducerExtension();
// Add two producers so when we remove the first it does a storage write, not a storage clear.
await pubSubGrain.RegisterProducer(streamId, firstProducer);
await pubSubGrain.RegisterProducer(streamId, secondProducer);
int producers = await pubSubGrain.ProducerCount(streamId);
Assert.Equal(2, producers);
// inject fault
await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when unregistering a producer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.UnregisterProducer(streamId, firstProducer));
// pubsub grain should recover and still function
await pubSubGrain.UnregisterProducer(streamId, firstProducer);
producers = await pubSubGrain.ProducerCount(streamId);
Assert.Equal(1, producers);
// inject clear fault, because removing last producers should trigger a clear storage call.
await faultGrain.AddFaultOnClear(pubSubGrain as GrainReference, new ApplicationException("Write"));
// expect exception when unregistering a consumer
await Assert.ThrowsAsync<OrleansException>(
() => pubSubGrain.UnregisterProducer(streamId, secondProducer));
// pubsub grain should recover and still function
await pubSubGrain.UnregisterProducer(streamId, secondProducer);
producers = await pubSubGrain.ConsumerCount(streamId);
Assert.Equal(0, producers);
}
[Serializable]
private class DummyStreamProducerExtension : IStreamProducerExtension
{
private readonly Guid id;
public DummyStreamProducerExtension()
{
id = Guid.NewGuid();
}
public Task AddSubscriber(GuidId subscriptionId, InternalStreamId streamId, IStreamConsumerExtension streamConsumer)
{
return Task.CompletedTask;
}
public Task RemoveSubscriber(GuidId subscriptionId, InternalStreamId streamId)
{
return Task.CompletedTask;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((DummyStreamProducerExtension)obj);
}
public override int GetHashCode()
{
return id.GetHashCode();
}
private bool Equals(DummyStreamProducerExtension other)
{
return id.Equals(other.id);
}
}
}
}
| |
// InflaterHuffmanTree.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// 2010-08-13 Sky Sanders - Modified for Silverlight 3/4 and Windows Phone 7
using System;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// Huffman tree used for inflation
/// </summary>
internal class InflaterHuffmanTree
{
#region Constants
const int MAX_BITLEN = 15;
#endregion
#region Instance Fields
short[] tree;
#endregion
/// <summary>
/// Literal length tree
/// </summary>
public static InflaterHuffmanTree defLitLenTree;
/// <summary>
/// Distance tree
/// </summary>
public static InflaterHuffmanTree defDistTree;
static InflaterHuffmanTree()
{
try {
byte[] codeLengths = new byte[288];
int i = 0;
while (i < 144) {
codeLengths[i++] = 8;
}
while (i < 256) {
codeLengths[i++] = 9;
}
while (i < 280) {
codeLengths[i++] = 7;
}
while (i < 288) {
codeLengths[i++] = 8;
}
defLitLenTree = new InflaterHuffmanTree(codeLengths);
codeLengths = new byte[32];
i = 0;
while (i < 32) {
codeLengths[i++] = 5;
}
defDistTree = new InflaterHuffmanTree(codeLengths);
} catch (Exception) {
throw new SharpZipBaseException("InflaterHuffmanTree: static tree length illegal");
}
}
#region Constructors
/// <summary>
/// Constructs a Huffman tree from the array of code lengths.
/// </summary>
/// <param name = "codeLengths">
/// the array of code lengths
/// </param>
public InflaterHuffmanTree(byte[] codeLengths)
{
BuildTree(codeLengths);
}
#endregion
void BuildTree(byte[] codeLengths)
{
int[] blCount = new int[MAX_BITLEN + 1];
int[] nextCode = new int[MAX_BITLEN + 1];
for (int i = 0; i < codeLengths.Length; i++) {
int bits = codeLengths[i];
if (bits > 0) {
blCount[bits]++;
}
}
int code = 0;
int treeSize = 512;
for (int bits = 1; bits <= MAX_BITLEN; bits++) {
nextCode[bits] = code;
code += blCount[bits] << (16 - bits);
if (bits >= 10) {
/* We need an extra table for bit lengths >= 10. */
int start = nextCode[bits] & 0x1ff80;
int end = code & 0x1ff80;
treeSize += (end - start) >> (16 - bits);
}
}
/* -jr comment this out! doesnt work for dynamic trees and pkzip 2.04g
if (code != 65536)
{
throw new SharpZipBaseException("Code lengths don't add up properly.");
}
*/
/* Now create and fill the extra tables from longest to shortest
* bit len. This way the sub trees will be aligned.
*/
tree = new short[treeSize];
int treePtr = 512;
for (int bits = MAX_BITLEN; bits >= 10; bits--) {
int end = code & 0x1ff80;
code -= blCount[bits] << (16 - bits);
int start = code & 0x1ff80;
for (int i = start; i < end; i += 1 << 7) {
tree[DeflaterHuffman.BitReverse(i)] = (short) ((-treePtr << 4) | bits);
treePtr += 1 << (bits-9);
}
}
for (int i = 0; i < codeLengths.Length; i++) {
int bits = codeLengths[i];
if (bits == 0) {
continue;
}
code = nextCode[bits];
int revcode = DeflaterHuffman.BitReverse(code);
if (bits <= 9) {
do {
tree[revcode] = (short) ((i << 4) | bits);
revcode += 1 << bits;
} while (revcode < 512);
} else {
int subTree = tree[revcode & 511];
int treeLen = 1 << (subTree & 15);
subTree = -(subTree >> 4);
do {
tree[subTree | (revcode >> 9)] = (short) ((i << 4) | bits);
revcode += 1 << bits;
} while (revcode < treeLen);
}
nextCode[bits] = code + (1 << (16 - bits));
}
}
/// <summary>
/// Reads the next symbol from input. The symbol is encoded using the
/// huffman tree.
/// </summary>
/// <param name="input">
/// input the input source.
/// </param>
/// <returns>
/// the next symbol, or -1 if not enough input is available.
/// </returns>
public int GetSymbol(StreamManipulator input)
{
int lookahead, symbol;
if ((lookahead = input.PeekBits(9)) >= 0) {
if ((symbol = tree[lookahead]) >= 0) {
input.DropBits(symbol & 15);
return symbol >> 4;
}
int subtree = -(symbol >> 4);
int bitlen = symbol & 15;
if ((lookahead = input.PeekBits(bitlen)) >= 0) {
symbol = tree[subtree | (lookahead >> 9)];
input.DropBits(symbol & 15);
return symbol >> 4;
} else {
int bits = input.AvailableBits;
lookahead = input.PeekBits(bits);
symbol = tree[subtree | (lookahead >> 9)];
if ((symbol & 15) <= bits) {
input.DropBits(symbol & 15);
return symbol >> 4;
} else {
return -1;
}
}
} else {
int bits = input.AvailableBits;
lookahead = input.PeekBits(bits);
symbol = tree[lookahead];
if (symbol >= 0 && (symbol & 15) <= bits) {
input.DropBits(symbol & 15);
return symbol >> 4;
} else {
return -1;
}
}
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="OutlookConfigurationSettings.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the OutlookConfigurationSettings class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Autodiscover
{
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Exchange.WebServices.Data;
/// <summary>
/// Represents Outlook configuration settings.
/// </summary>
internal sealed class OutlookConfigurationSettings : ConfigurationSettingsBase
{
#region Static fields
/// <summary>
/// All user settings that are available from the Outlook provider.
/// </summary>
private static LazyMember<List<UserSettingName>> allOutlookProviderSettings = new LazyMember<List<UserSettingName>>(
() =>
{
List<UserSettingName> results = new List<UserSettingName>();
results.AddRange(OutlookUser.AvailableUserSettings);
results.AddRange(OutlookProtocol.AvailableUserSettings);
results.Add(UserSettingName.AlternateMailboxes);
return results;
});
#endregion
#region Private fields
private OutlookUser user;
private OutlookAccount account;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="OutlookConfigurationSettings"/> class.
/// </summary>
public OutlookConfigurationSettings()
{
this.user = new OutlookUser();
this.account = new OutlookAccount();
}
/// <summary>
/// Determines whether user setting is available in the OutlookConfiguration or not.
/// </summary>
/// <param name="setting">The setting.</param>
/// <returns>True if user setting is available, otherwise, false.
/// </returns>
internal static bool IsAvailableUserSetting(UserSettingName setting)
{
return allOutlookProviderSettings.Member.Contains(setting);
}
/// <summary>
/// Gets the namespace that defines the settings.
/// </summary>
/// <returns>The namespace that defines the settings.</returns>
internal override string GetNamespace()
{
return "http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a";
}
/// <summary>
/// Makes this instance a redirection response.
/// </summary>
/// <param name="redirectUrl">The redirect URL.</param>
internal override void MakeRedirectionResponse(Uri redirectUrl)
{
this.account = new OutlookAccount()
{
RedirectTarget = redirectUrl.ToString(),
ResponseType = AutodiscoverResponseType.RedirectUrl
};
}
/// <summary>
/// Tries to read the current XML element.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True is the current element was read, false otherwise.</returns>
internal override bool TryReadCurrentXmlElement(EwsXmlReader reader)
{
if (!base.TryReadCurrentXmlElement(reader))
{
switch (reader.LocalName)
{
case XmlElementNames.User:
this.user.LoadFromXml(reader);
return true;
case XmlElementNames.Account:
this.account.LoadFromXml(reader);
return true;
default:
reader.SkipCurrentElement();
return false;
}
}
else
{
return true;
}
}
/// <summary>
/// Convert OutlookConfigurationSettings to GetUserSettings response.
/// </summary>
/// <param name="smtpAddress">SMTP address requested.</param>
/// <param name="requestedSettings">The requested settings.</param>
/// <returns>GetUserSettingsResponse</returns>
internal override GetUserSettingsResponse ConvertSettings(string smtpAddress, List<UserSettingName> requestedSettings)
{
GetUserSettingsResponse response = new GetUserSettingsResponse();
response.SmtpAddress = smtpAddress;
if (this.Error != null)
{
response.ErrorCode = AutodiscoverErrorCode.InternalServerError;
response.ErrorMessage = this.Error.Message;
}
else
{
switch (this.ResponseType)
{
case AutodiscoverResponseType.Success:
response.ErrorCode = AutodiscoverErrorCode.NoError;
response.ErrorMessage = string.Empty;
this.user.ConvertToUserSettings(requestedSettings, response);
this.account.ConvertToUserSettings(requestedSettings, response);
this.ReportUnsupportedSettings(requestedSettings, response);
break;
case AutodiscoverResponseType.Error:
response.ErrorCode = AutodiscoverErrorCode.InternalServerError;
response.ErrorMessage = Strings.InvalidAutodiscoverServiceResponse;
break;
case AutodiscoverResponseType.RedirectAddress:
response.ErrorCode = AutodiscoverErrorCode.RedirectAddress;
response.ErrorMessage = string.Empty;
response.RedirectTarget = this.RedirectTarget;
break;
case AutodiscoverResponseType.RedirectUrl:
response.ErrorCode = AutodiscoverErrorCode.RedirectUrl;
response.ErrorMessage = string.Empty;
response.RedirectTarget = this.RedirectTarget;
break;
default:
EwsUtilities.Assert(
false,
"OutlookConfigurationSettings.ConvertSettings",
"An unexpected error has occured. This code path should never be reached.");
break;
}
}
return response;
}
/// <summary>
/// Reports any requested user settings that aren't supported by the Outlook provider.
/// </summary>
/// <param name="requestedSettings">The requested settings.</param>
/// <param name="response">The response.</param>
private void ReportUnsupportedSettings(List<UserSettingName> requestedSettings, GetUserSettingsResponse response)
{
// In English: find settings listed in requestedSettings that are not supported by the Legacy provider.
IEnumerable<UserSettingName> invalidSettingQuery = from setting in requestedSettings
where !OutlookConfigurationSettings.IsAvailableUserSetting(setting)
select setting;
// Add any unsupported settings to the UserSettingsError collection.
foreach (UserSettingName invalidSetting in invalidSettingQuery)
{
UserSettingError settingError = new UserSettingError()
{
ErrorCode = AutodiscoverErrorCode.InvalidSetting,
SettingName = invalidSetting.ToString(),
ErrorMessage = string.Format(Strings.AutodiscoverInvalidSettingForOutlookProvider, invalidSetting.ToString())
};
response.UserSettingErrors.Add(settingError);
}
}
/// <summary>
/// Gets the type of the response.
/// </summary>
/// <value>The type of the response.</value>
internal override AutodiscoverResponseType ResponseType
{
get
{
if (this.account != null)
{
return this.account.ResponseType;
}
else
{
return AutodiscoverResponseType.Error;
}
}
}
/// <summary>
/// Gets the redirect target.
/// </summary>
internal override string RedirectTarget
{
get
{
return this.account.RedirectTarget;
}
}
}
}
| |
namespace Humidifier.IoT
{
using System.Collections.Generic;
using TopicRuleTypes;
public class TopicRule : Humidifier.Resource
{
public static class Attributes
{
public static string Arn = "Arn" ;
}
public override string AWSTypeName
{
get
{
return @"AWS::IoT::TopicRule";
}
}
/// <summary>
/// RuleName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-topicrule.html#cfn-iot-topicrule-rulename
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic RuleName
{
get;
set;
}
/// <summary>
/// TopicRulePayload
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-topicrule.html#cfn-iot-topicrule-topicrulepayload
/// Required: True
/// UpdateType: Mutable
/// Type: TopicRulePayload
/// </summary>
public TopicRulePayload TopicRulePayload
{
get;
set;
}
}
namespace TopicRuleTypes
{
public class S3Action
{
/// <summary>
/// BucketName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-s3action.html#cfn-iot-topicrule-s3action-bucketname
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic BucketName
{
get;
set;
}
/// <summary>
/// Key
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-s3action.html#cfn-iot-topicrule-s3action-key
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Key
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-s3action.html#cfn-iot-topicrule-s3action-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
}
public class SqsAction
{
/// <summary>
/// QueueUrl
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-sqsaction.html#cfn-iot-topicrule-sqsaction-queueurl
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic QueueUrl
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-sqsaction.html#cfn-iot-topicrule-sqsaction-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// UseBase64
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-sqsaction.html#cfn-iot-topicrule-sqsaction-usebase64
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic UseBase64
{
get;
set;
}
}
public class PutItemInput
{
/// <summary>
/// TableName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-putiteminput.html#cfn-iot-topicrule-putiteminput-tablename
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic TableName
{
get;
set;
}
}
public class SnsAction
{
/// <summary>
/// MessageFormat
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-snsaction.html#cfn-iot-topicrule-snsaction-messageformat
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MessageFormat
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-snsaction.html#cfn-iot-topicrule-snsaction-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// TargetArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-snsaction.html#cfn-iot-topicrule-snsaction-targetarn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic TargetArn
{
get;
set;
}
}
public class FirehoseAction
{
/// <summary>
/// DeliveryStreamName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-firehoseaction.html#cfn-iot-topicrule-firehoseaction-deliverystreamname
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DeliveryStreamName
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-firehoseaction.html#cfn-iot-topicrule-firehoseaction-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// Separator
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-firehoseaction.html#cfn-iot-topicrule-firehoseaction-separator
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Separator
{
get;
set;
}
}
public class LambdaAction
{
/// <summary>
/// FunctionArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-lambdaaction.html#cfn-iot-topicrule-lambdaaction-functionarn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic FunctionArn
{
get;
set;
}
}
public class ElasticsearchAction
{
/// <summary>
/// Endpoint
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-elasticsearchaction.html#cfn-iot-topicrule-elasticsearchaction-endpoint
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Endpoint
{
get;
set;
}
/// <summary>
/// Id
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-elasticsearchaction.html#cfn-iot-topicrule-elasticsearchaction-id
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Id
{
get;
set;
}
/// <summary>
/// Index
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-elasticsearchaction.html#cfn-iot-topicrule-elasticsearchaction-index
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Index
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-elasticsearchaction.html#cfn-iot-topicrule-elasticsearchaction-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// Type
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-elasticsearchaction.html#cfn-iot-topicrule-elasticsearchaction-type
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Type
{
get;
set;
}
}
public class DynamoDBAction
{
/// <summary>
/// HashKeyField
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-hashkeyfield
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HashKeyField
{
get;
set;
}
/// <summary>
/// HashKeyType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-hashkeytype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HashKeyType
{
get;
set;
}
/// <summary>
/// HashKeyValue
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-hashkeyvalue
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HashKeyValue
{
get;
set;
}
/// <summary>
/// PayloadField
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-payloadfield
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic PayloadField
{
get;
set;
}
/// <summary>
/// RangeKeyField
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-rangekeyfield
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RangeKeyField
{
get;
set;
}
/// <summary>
/// RangeKeyType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-rangekeytype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RangeKeyType
{
get;
set;
}
/// <summary>
/// RangeKeyValue
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-rangekeyvalue
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RangeKeyValue
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// TableName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-tablename
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic TableName
{
get;
set;
}
}
public class KinesisAction
{
/// <summary>
/// PartitionKey
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-kinesisaction.html#cfn-iot-topicrule-kinesisaction-partitionkey
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic PartitionKey
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-kinesisaction.html#cfn-iot-topicrule-kinesisaction-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// StreamName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-kinesisaction.html#cfn-iot-topicrule-kinesisaction-streamname
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic StreamName
{
get;
set;
}
}
public class Action
{
/// <summary>
/// CloudwatchAlarm
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-cloudwatchalarm
/// Required: False
/// UpdateType: Mutable
/// Type: CloudwatchAlarmAction
/// </summary>
public CloudwatchAlarmAction CloudwatchAlarm
{
get;
set;
}
/// <summary>
/// CloudwatchMetric
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-cloudwatchmetric
/// Required: False
/// UpdateType: Mutable
/// Type: CloudwatchMetricAction
/// </summary>
public CloudwatchMetricAction CloudwatchMetric
{
get;
set;
}
/// <summary>
/// DynamoDB
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-dynamodb
/// Required: False
/// UpdateType: Mutable
/// Type: DynamoDBAction
/// </summary>
public DynamoDBAction DynamoDB
{
get;
set;
}
/// <summary>
/// DynamoDBv2
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-dynamodbv2
/// Required: False
/// UpdateType: Mutable
/// Type: DynamoDBv2Action
/// </summary>
public DynamoDBv2Action DynamoDBv2
{
get;
set;
}
/// <summary>
/// Elasticsearch
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-elasticsearch
/// Required: False
/// UpdateType: Mutable
/// Type: ElasticsearchAction
/// </summary>
public ElasticsearchAction Elasticsearch
{
get;
set;
}
/// <summary>
/// Firehose
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-firehose
/// Required: False
/// UpdateType: Mutable
/// Type: FirehoseAction
/// </summary>
public FirehoseAction Firehose
{
get;
set;
}
/// <summary>
/// IotAnalytics
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-iotanalytics
/// Required: False
/// UpdateType: Mutable
/// Type: IotAnalyticsAction
/// </summary>
public IotAnalyticsAction IotAnalytics
{
get;
set;
}
/// <summary>
/// Kinesis
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-kinesis
/// Required: False
/// UpdateType: Mutable
/// Type: KinesisAction
/// </summary>
public KinesisAction Kinesis
{
get;
set;
}
/// <summary>
/// Lambda
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-lambda
/// Required: False
/// UpdateType: Mutable
/// Type: LambdaAction
/// </summary>
public LambdaAction Lambda
{
get;
set;
}
/// <summary>
/// Republish
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-republish
/// Required: False
/// UpdateType: Mutable
/// Type: RepublishAction
/// </summary>
public RepublishAction Republish
{
get;
set;
}
/// <summary>
/// S3
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-s3
/// Required: False
/// UpdateType: Mutable
/// Type: S3Action
/// </summary>
public S3Action S3
{
get;
set;
}
/// <summary>
/// Sns
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-sns
/// Required: False
/// UpdateType: Mutable
/// Type: SnsAction
/// </summary>
public SnsAction Sns
{
get;
set;
}
/// <summary>
/// Sqs
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-sqs
/// Required: False
/// UpdateType: Mutable
/// Type: SqsAction
/// </summary>
public SqsAction Sqs
{
get;
set;
}
/// <summary>
/// StepFunctions
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-stepfunctions
/// Required: False
/// UpdateType: Mutable
/// Type: StepFunctionsAction
/// </summary>
public StepFunctionsAction StepFunctions
{
get;
set;
}
}
public class IotAnalyticsAction
{
/// <summary>
/// ChannelName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-iotanalyticsaction.html#cfn-iot-topicrule-iotanalyticsaction-channelname
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ChannelName
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-iotanalyticsaction.html#cfn-iot-topicrule-iotanalyticsaction-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
}
public class RepublishAction
{
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-republishaction.html#cfn-iot-topicrule-republishaction-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// Topic
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-republishaction.html#cfn-iot-topicrule-republishaction-topic
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Topic
{
get;
set;
}
}
public class StepFunctionsAction
{
/// <summary>
/// ExecutionNamePrefix
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-stepfunctionsaction.html#cfn-iot-topicrule-stepfunctionsaction-executionnameprefix
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ExecutionNamePrefix
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-stepfunctionsaction.html#cfn-iot-topicrule-stepfunctionsaction-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// StateMachineName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-stepfunctionsaction.html#cfn-iot-topicrule-stepfunctionsaction-statemachinename
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic StateMachineName
{
get;
set;
}
}
public class TopicRulePayload
{
/// <summary>
/// Actions
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html#cfn-iot-topicrule-topicrulepayload-actions
/// Required: True
/// UpdateType: Mutable
/// Type: List
/// ItemType: Action
/// </summary>
public List<Action> Actions
{
get;
set;
}
/// <summary>
/// AwsIotSqlVersion
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html#cfn-iot-topicrule-topicrulepayload-awsiotsqlversion
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic AwsIotSqlVersion
{
get;
set;
}
/// <summary>
/// Description
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html#cfn-iot-topicrule-topicrulepayload-description
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Description
{
get;
set;
}
/// <summary>
/// ErrorAction
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html#cfn-iot-topicrule-topicrulepayload-erroraction
/// Required: False
/// UpdateType: Mutable
/// Type: Action
/// </summary>
public Action ErrorAction
{
get;
set;
}
/// <summary>
/// RuleDisabled
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html#cfn-iot-topicrule-topicrulepayload-ruledisabled
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic RuleDisabled
{
get;
set;
}
/// <summary>
/// Sql
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html#cfn-iot-topicrule-topicrulepayload-sql
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Sql
{
get;
set;
}
}
public class DynamoDBv2Action
{
/// <summary>
/// PutItem
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbv2action.html#cfn-iot-topicrule-dynamodbv2action-putitem
/// Required: False
/// UpdateType: Mutable
/// Type: PutItemInput
/// </summary>
public PutItemInput PutItem
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbv2action.html#cfn-iot-topicrule-dynamodbv2action-rolearn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
}
public class CloudwatchAlarmAction
{
/// <summary>
/// AlarmName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchalarmaction.html#cfn-iot-topicrule-cloudwatchalarmaction-alarmname
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic AlarmName
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchalarmaction.html#cfn-iot-topicrule-cloudwatchalarmaction-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// StateReason
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchalarmaction.html#cfn-iot-topicrule-cloudwatchalarmaction-statereason
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic StateReason
{
get;
set;
}
/// <summary>
/// StateValue
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchalarmaction.html#cfn-iot-topicrule-cloudwatchalarmaction-statevalue
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic StateValue
{
get;
set;
}
}
public class CloudwatchMetricAction
{
/// <summary>
/// MetricName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-metricname
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MetricName
{
get;
set;
}
/// <summary>
/// MetricNamespace
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-metricnamespace
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MetricNamespace
{
get;
set;
}
/// <summary>
/// MetricTimestamp
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-metrictimestamp
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MetricTimestamp
{
get;
set;
}
/// <summary>
/// MetricUnit
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-metricunit
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MetricUnit
{
get;
set;
}
/// <summary>
/// MetricValue
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-metricvalue
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MetricValue
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-rolearn
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
}
}
}
| |
//
// WindowBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
// Andres G. Aragoneses <andres.aragoneses@7digital.com>
// Konrad M. Kruczynski <kkruczynski@antmicro.com>
//
// Copyright (c) 2011 Xamarin Inc
// Copyright (c) 2012 7Digital Media Ltd
// Copyright (c) 2016 Antmicro Ltd
//
// 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.Linq;
using AppKit;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.Mac
{
public class WindowBackend: NSWindow, IWindowBackend
{
WindowBackendController controller;
IWindowFrameEventSink eventSink;
Window frontend;
ViewBackend child;
NSView childView;
bool sensitive = true;
public WindowBackend (IntPtr ptr): base (ptr)
{
}
public WindowBackend ()
{
this.controller = new WindowBackendController ();
controller.Window = this;
StyleMask |= NSWindowStyle.Resizable | NSWindowStyle.Closable | NSWindowStyle.Miniaturizable;
AutorecalculatesKeyViewLoop = true;
ContentView.AutoresizesSubviews = true;
ContentView.Hidden = true;
// TODO: do it only if mouse move events are enabled in a widget
AcceptsMouseMovedEvents = true;
WillClose += delegate {
OnClosed ();
};
Center ();
}
object IWindowFrameBackend.Window {
get { return this; }
}
public IntPtr NativeHandle {
get { return Handle; }
}
public IWindowFrameEventSink EventSink {
get { return (IWindowFrameEventSink)eventSink; }
}
public virtual void InitializeBackend (object frontend, ApplicationContext context)
{
this.ApplicationContext = context;
this.frontend = (Window) frontend;
}
public void Initialize (IWindowFrameEventSink eventSink)
{
this.eventSink = eventSink;
}
public ApplicationContext ApplicationContext {
get;
private set;
}
public object NativeWidget {
get {
return this;
}
}
public string Name { get; set; }
internal void InternalShow ()
{
MakeKeyAndOrderFront (MacEngine.App);
if (ParentWindow != null)
{
if (!ParentWindow.ChildWindows.Contains(this))
ParentWindow.AddChildWindow(this, NSWindowOrderingMode.Above);
// always use NSWindow for alignment when running in guest mode and
// don't rely on AddChildWindow to position the window correctly
if (frontend.InitialLocation == WindowLocation.CenterParent && !(ParentWindow is WindowBackend))
{
var parentBounds = MacDesktopBackend.ToDesktopRect(ParentWindow.ContentRectFor(ParentWindow.Frame));
var bounds = ((IWindowFrameBackend)this).Bounds;
bounds.X = parentBounds.Center.X - (Frame.Width / 2);
bounds.Y = parentBounds.Center.Y - (Frame.Height / 2);
((IWindowFrameBackend)this).Bounds = bounds;
}
}
}
public void Present ()
{
InternalShow();
}
public bool Visible {
get {
return IsVisible;
}
set {
if (value)
MacEngine.App.ShowWindow(this);
ContentView.Hidden = !value; // handle shown/hidden events
IsVisible = value;
}
}
public double Opacity {
get { return AlphaValue; }
set { AlphaValue = (float)value; }
}
Color IWindowBackend.BackgroundColor {
get {
return BackgroundColor.ToXwtColor ();
}
set {
BackgroundColor = value.ToNSColor ();
}
}
public bool Sensitive {
get {
return sensitive;
}
set {
sensitive = value;
if (child != null)
child.UpdateSensitiveStatus (child.Widget, sensitive);
}
}
public bool HasFocus {
get {
return IsKeyWindow;
}
}
public WindowState WindowState {
get {
if (MacSystemInformation.OsVersion < MacSystemInformation.Lion)
return WindowState.Normal;
if (isWindowSateDelayed) // rare case while "unfullscreening"
return delayedWindowState;
if (IsMiniaturized)
return WindowState.Iconified;
if ((StyleMask & NSWindowStyle.FullScreenWindow) != 0)
return WindowState.FullScreen;
if (IsZoomed)
return WindowState.Maximized;
else
return WindowState.Normal;
}
set {
if (MacSystemInformation.OsVersion < MacSystemInformation.Lion)
return;
if ((value != Xwt.WindowState.FullScreen) && ((StyleMask & NSWindowStyle.FullScreenWindow) != 0)) {
// always unfullscreen first
// and delay setting new state
ToggleFullScreen (this);
CollectionBehavior &= ~NSWindowCollectionBehavior.FullScreenPrimary;
isWindowSateDelayed = true;
delayedWindowState = value;
DidExitFullScreen += DelayedSetWindowState;
return;
}
if ((value == Xwt.WindowState.Iconified) && !IsMiniaturized) {
// Currently not iconified.
Miniaturize (this);
} else if ((value == Xwt.WindowState.FullScreen) && ((StyleMask & NSWindowStyle.FullScreenWindow) == 0)) {
// Currently not full screen.
CollectionBehavior |= NSWindowCollectionBehavior.FullScreenPrimary;
ToggleFullScreen (this);
} else if ((value == Xwt.WindowState.Maximized) && !IsZoomed) {
// Currently not maximized.
PerformZoom (this);
} else {
if (IsMiniaturized)
// Currently iconified.
Deminiaturize (this);
else if (IsZoomed)
// Currently full screen.
PerformZoom (this);
}
}
}
bool isWindowSateDelayed;
WindowState delayedWindowState;
void DelayedSetWindowState (object sender, EventArgs args)
{
WindowState = delayedWindowState;
DidExitFullScreen -= DelayedSetWindowState;
isWindowSateDelayed = false;
}
object IWindowFrameBackend.Screen {
get {
return Screen;
}
}
#region IWindowBackend implementation
void IBackend.EnableEvent (object eventId)
{
if (eventId is WindowFrameEvent) {
var @event = (WindowFrameEvent)eventId;
switch (@event) {
case WindowFrameEvent.BoundsChanged:
DidResize += HandleDidResize;
DidMove += HandleDidResize;
break;
case WindowFrameEvent.Hidden:
EnableVisibilityEvent (@event);
this.WillClose += OnWillClose;
break;
case WindowFrameEvent.Shown:
EnableVisibilityEvent (@event);
break;
case WindowFrameEvent.CloseRequested:
WindowShouldClose = OnShouldClose;
break;
}
}
}
void OnWillClose (object sender, EventArgs args) {
OnHidden ();
}
bool OnShouldClose (NSObject ob)
{
return closePerformed = RequestClose ();
}
internal bool RequestClose ()
{
bool res = true;
ApplicationContext.InvokeUserCode (() => res = eventSink.OnCloseRequested ());
return res;
}
protected virtual void OnClosed ()
{
if (!disposing)
ApplicationContext.InvokeUserCode (eventSink.OnClosed);
}
bool closePerformed;
bool IWindowFrameBackend.Close ()
{
closePerformed = true;
if ((StyleMask & NSWindowStyle.Titled) != 0 && (StyleMask & NSWindowStyle.Closable) != 0)
PerformClose(this);
else
Close ();
if (ParentWindow != null)
ParentWindow.RemoveChildWindow(this);
return closePerformed;
}
bool VisibilityEventsEnabled ()
{
return eventsEnabled != WindowFrameEvent.BoundsChanged;
}
WindowFrameEvent eventsEnabled = WindowFrameEvent.BoundsChanged;
NSString HiddenProperty {
get { return new NSString ("hidden"); }
}
void EnableVisibilityEvent (WindowFrameEvent ev)
{
if (!VisibilityEventsEnabled ()) {
ContentView.AddObserver (this, HiddenProperty, NSKeyValueObservingOptions.New, IntPtr.Zero);
}
if (!eventsEnabled.HasFlag (ev)) {
eventsEnabled |= ev;
}
}
public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
{
if (keyPath.ToString () == HiddenProperty.ToString () && ofObject.Equals (ContentView)) {
if (ContentView.Hidden) {
if (eventsEnabled.HasFlag (WindowFrameEvent.Hidden)) {
OnHidden ();
}
} else {
if (eventsEnabled.HasFlag (WindowFrameEvent.Shown)) {
OnShown ();
}
}
}
}
void OnHidden () {
ApplicationContext.InvokeUserCode (delegate ()
{
eventSink.OnHidden ();
});
}
void OnShown () {
ApplicationContext.InvokeUserCode (delegate ()
{
eventSink.OnShown ();
});
}
void DisableVisibilityEvent (WindowFrameEvent ev)
{
if (eventsEnabled.HasFlag (ev)) {
eventsEnabled ^= ev;
if (!VisibilityEventsEnabled ()) {
ContentView.RemoveObserver (this, HiddenProperty);
}
}
}
void IBackend.DisableEvent (object eventId)
{
if (eventId is WindowFrameEvent) {
var @event = (WindowFrameEvent)eventId;
switch (@event) {
case WindowFrameEvent.BoundsChanged:
DidResize -= HandleDidResize;
DidMove -= HandleDidResize;
break;
case WindowFrameEvent.Hidden:
this.WillClose -= OnWillClose;
DisableVisibilityEvent (@event);
break;
case WindowFrameEvent.Shown:
DisableVisibilityEvent (@event);
break;
}
}
}
void HandleDidResize (object sender, EventArgs e)
{
OnBoundsChanged ();
}
protected virtual void OnBoundsChanged ()
{
LayoutWindow ();
ApplicationContext.InvokeUserCode (delegate {
eventSink.OnBoundsChanged (((IWindowBackend)this).Bounds);
});
}
void IWindowBackend.SetChild (IWidgetBackend child)
{
if (this.child != null) {
ViewBackend.RemoveChildPlacement (this.child.Widget);
this.child.Widget.RemoveFromSuperview ();
childView = null;
}
this.child = (ViewBackend) child;
if (child != null) {
childView = ViewBackend.GetWidgetWithPlacement (child);
ContentView.AddSubview (childView);
LayoutWindow ();
childView.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable;
}
}
public virtual void UpdateChildPlacement (IWidgetBackend childBackend)
{
var w = ViewBackend.SetChildPlacement (childBackend);
LayoutWindow ();
w.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable;
}
bool IWindowFrameBackend.Decorated {
get {
return (StyleMask & NSWindowStyle.Titled) != 0;
}
set {
if (value)
StyleMask |= NSWindowStyle.Titled;
else
StyleMask &= ~(NSWindowStyle.Titled | NSWindowStyle.Borderless);
}
}
bool IWindowFrameBackend.ShowInTaskbar {
get {
return false;
}
set {
}
}
void IWindowFrameBackend.SetTransientFor (IWindowFrameBackend window)
{
if (!((IWindowFrameBackend)this).ShowInTaskbar)
StyleMask &= ~NSWindowStyle.Miniaturizable;
var win = window as NSWindow ?? ApplicationContext.Toolkit.GetNativeWindow(window) as NSWindow;
if (ParentWindow != win) {
// remove from the previous parent
if (ParentWindow != null)
ParentWindow.RemoveChildWindow(this);
ParentWindow = win;
// A window must be visible to be added to a parent. See InternalShow().
if (Visible)
ParentWindow.AddChildWindow(this, NSWindowOrderingMode.Above);
}
}
bool IWindowFrameBackend.Resizable {
get {
return (StyleMask & NSWindowStyle.Resizable) != 0;
}
set {
if (value)
StyleMask |= NSWindowStyle.Resizable;
else
StyleMask &= ~NSWindowStyle.Resizable;
}
}
public void SetPadding (double left, double top, double right, double bottom)
{
LayoutWindow ();
}
void IWindowFrameBackend.Move (double x, double y)
{
var r = FrameRectFor (new CGRect ((nfloat)x, (nfloat)y, Frame.Width, Frame.Height));
SetFrame (r, true);
}
void IWindowFrameBackend.SetSize (double width, double height)
{
var cr = ContentRectFor (Frame);
if (width == -1)
width = cr.Width;
if (height == -1)
height = cr.Height;
var r = FrameRectFor (new CGRect ((nfloat)cr.X, (nfloat)cr.Y, (nfloat)width, (nfloat)height));
SetFrame (r, true);
LayoutWindow ();
}
Rectangle IWindowFrameBackend.Bounds {
get {
var b = ContentRectFor (Frame);
var r = MacDesktopBackend.ToDesktopRect (b);
return new Rectangle ((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height);
}
set {
var r = MacDesktopBackend.FromDesktopRect (value);
var fr = FrameRectFor (r);
SetFrame (fr, true);
}
}
public void SetMainMenu (IMenuBackend menu)
{
var m = (MenuBackend) menu;
m.SetMainMenuMode ();
NSApplication.SharedApplication.Menu = m;
// base.Menu = m;
}
#endregion
static Selector closeSel = new Selector ("close");
bool disposing, disposed;
protected override void Dispose(bool disposing)
{
if (!disposed && disposing)
{
this.disposing = true;
try
{
if (VisibilityEventsEnabled() && ContentView != null)
ContentView.RemoveObserver(this, HiddenProperty);
// HACK: Xamarin.Mac/MonoMac limitation: no direct way to release a window manually
// A NSWindow instance will be removed from NSApplication.SharedApplication.Windows
// only if it is being closed with ReleasedWhenClosed set to true but not on Dispose
// and there is no managed way to tell Cocoa to release the window manually (and to
// remove it from the active window list).
// see also: https://bugzilla.xamarin.com/show_bug.cgi?id=45298
// WORKAROUND:
// bump native reference count by calling DangerousRetain()
// base.Dispose will now unref the window correctly without crashing
DangerousRetain();
// tell Cocoa to release the window on Close
ReleasedWhenClosed = true;
// Close the window (Cocoa will do its job even if the window is already closed)
Messaging.void_objc_msgSend (this.Handle, closeSel.Handle);
} finally {
this.disposing = false;
this.disposed = true;
}
}
if (controller != null) {
controller.Dispose ();
controller = null;
}
base.Dispose (disposing);
}
public void DragStart (TransferDataSource data, DragDropAction dragAction, object dragImage, double xhot, double yhot)
{
throw new NotImplementedException ();
}
public void SetDragSource (string[] types, DragDropAction dragAction)
{
}
public void SetDragTarget (string[] types, DragDropAction dragAction)
{
}
public virtual void SetMinSize (Size s)
{
var b = ((IWindowBackend)this).Bounds;
if (b.Size.Width < s.Width)
b.Width = s.Width;
if (b.Size.Height < s.Height)
b.Height = s.Height;
if (b != ((IWindowBackend)this).Bounds)
((IWindowBackend)this).Bounds = b;
var r = FrameRectFor (new CGRect (0, 0, (nfloat)s.Width, (nfloat)s.Height));
MinSize = r.Size;
}
public void SetIcon (ImageDescription icon)
{
}
public virtual void GetMetrics (out Size minSize, out Size decorationSize)
{
minSize = decorationSize = Size.Zero;
}
public virtual void LayoutWindow ()
{
LayoutContent (ContentView.Frame);
}
public void LayoutContent (CGRect frame)
{
if (child != null) {
frame.X += (nfloat) frontend.Padding.Left;
frame.Width -= (nfloat) (frontend.Padding.HorizontalSpacing);
frame.Y += (nfloat) (childView.IsFlipped ? frontend.Padding.Bottom : frontend.Padding.Top);
frame.Height -= (nfloat) (frontend.Padding.VerticalSpacing);
childView.Frame = frame;
}
}
}
public partial class WindowBackendController : NSWindowController
{
public WindowBackendController ()
{
}
}
}
| |
using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Xunit;
namespace Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests.VersioningAndUnification.AppConfig
{
public sealed class FilePrimary : ResolveAssemblyReferenceTestFixture
{
/// <summary>
/// In this case,
/// - A single primary file reference to assembly version 1.0.0.0 was passed in.
/// - An app.config was passed in that promotes assembly version from 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void Exists()
{
// This WriteLine is a hack. On a slow machine, the Tasks unittest fails because remoting
// times out the object used for remoting console writes. Adding a write in the middle of
// keeps remoting from timing out the object.
Console.WriteLine("Performing VersioningAndUnification.AppConfig.FilePrimary.Exists() test");
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"C:\MyComponents\v1.0\UnifyMe.dll")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.AssemblyFiles = assemblyFiles;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// Test the case where the appconfig has a malformed binding redirect version.
/// </summary>
[Fact]
public void BadAppconfigOldVersion()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"C:\MyComponents\v1.0\UnifyMe.dll")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <runtime>\n" +
"<assemblyBinding xmlns='urn:schemas-microsoft-com:asm.v1'>\n" +
"<dependentAssembly>\n" +
"<assemblyIdentity name='Micron.Facilities.Data' publicKeyToken='2D8C82D3A1452EF1' culture='neutral'/>\n" +
"<bindingRedirect oldVersion='1.*' newVersion='2.0.0.0'/>\n" +
"</dependentAssembly>\n" +
"</assemblyBinding>\n" +
"</runtime>\n"
);
try
{
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.AssemblyFiles = assemblyFiles;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.False(succeeded);
engine.AssertLogContains("MSB3249");
}
finally
{
if (File.Exists(appConfigFile))
{
// Cleanup.
File.Delete(appConfigFile);
}
}
}
/// <summary>
/// Test the case where the appconfig has a malformed binding redirect version.
/// </summary>
[Fact]
public void BadAppconfigNewVersion()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"C:\MyComponents\v1.0\UnifyMe.dll")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <runtime>\n" +
"<assemblyBinding xmlns='urn:schemas-microsoft-com:asm.v1'>\n" +
"<dependentAssembly>\n" +
"<assemblyIdentity name='Micron.Facilities.Data' publicKeyToken='2D8C82D3A1452EF1' culture='neutral'/>\n" +
"<bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.*.0'/>\n" +
"</dependentAssembly>\n" +
"</assemblyBinding>\n" +
"</runtime>\n"
);
try
{
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.AssemblyFiles = assemblyFiles;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.False(succeeded);
engine.AssertLogContains("MSB3249");
}
finally
{
if (File.Exists(appConfigFile))
{
// Cleanup.
File.Delete(appConfigFile);
}
}
}
/// <summary>
/// In this case,
/// - A single reference to DependsOnUnified was passed in.
/// - This assembly depends on version 1.0.0.0 of UnifyMe.
/// - An app.config was passed in that promotes UnifyMe version from 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of UnifyMe exists.
/// - Version 2.0.0.0 of UnifyMe exists.
/// -Version 2.0.0.0 of UnifyMe is in the Black List
/// Expected:
/// - There should be a warning indicating that DependsOnUnified has a dependency UnifyMe 2.0.0.0 which is not in a TargetFrameworkSubset.
/// - There will be no unified message.
/// Rationale:
/// Strongly named dependencies should unify according to the bindingRedirects in the app.config, if the unified version is in the black list it should be removed and warned.
/// </summary>
[Fact]
public void ExistsPromotedDependencyInTheBlackList()
{
string implicitRedistListContents =
"<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
"<File AssemblyName='UniFYme' Version='2.0.0.0' Culture='neutral' PublicKeyToken='b77a5c561934e089' InGAC='false' />" +
"</FileList >";
string engineOnlySubset =
"<FileList Redist='Microsoft-Windows-CLRCoreComp' >" +
"<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" +
"</FileList >";
string redistListPath = FileUtilities.GetTemporaryFile();
string subsetListPath = FileUtilities.GetTemporaryFile();
string appConfigFile = null;
try
{
File.WriteAllText(redistListPath, implicitRedistListContents);
File.WriteAllText(subsetListPath, engineOnlySubset);
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("DependsOnUnified, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
// Construct the app.config.
appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.InstalledAssemblyTables = new TaskItem[] { new TaskItem(redistListPath) };
t.InstalledAssemblySubsetTables = new TaskItem[] { new TaskItem(subsetListPath) };
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(0, t.ResolvedDependencyFiles.Length);
engine.AssertLogDoesntContain
(
String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, @"C:\MyApp\v1.0\DependsOnUnified.dll")
);
}
finally
{
File.Delete(redistListPath);
File.Delete(subsetListPath);
// Cleanup.
File.Delete(appConfigFile);
}
}
/// <summary>
/// In this case,
/// - A single primary file reference to assembly version 1.0.0.0 was passed in.
/// - An app.config was passed in that promotes a *different* assembly version name from
// 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// - The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// One entry in the app.config file should not be able to impact the mapping of an assembly
/// with a different name.
/// </summary>
[Fact]
public void ExistsDifferentName()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"C:\MyComponents\v1.0\UnifyMe.dll")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='DontUnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.AssemblyFiles = assemblyFiles;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary file reference to assembly version 1.0.0.0 was passed in.
/// - An app.config was passed in that promotes assembly version from range 0.0.0.0-1.5.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// - The resulting assembly returned should be 2.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void ExistsOldVersionRange()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"C:\MyComponents\v1.0\UnifyMe.dll")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='0.0.0.0-1.5.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.AssemblyFiles = assemblyFiles;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary file reference to assembly version 1.0.0.0 was passed in.
/// - An app.config was passed in that promotes assembly version from 1.0.0.0 to 4.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 4.0.0.0 of the file *does not* exist.
/// Expected:
/// -- The resulting assembly returned should be 2.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void HighVersionDoesntExist()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"C:\MyComponents\v1.0\UnifyMe.dll")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='4.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.AssemblyFiles = assemblyFiles;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary file reference to assembly version 0.5.0.0 was passed in.
/// - An app.config was passed in that promotes assembly version from 0.0.0.0-2.0.0.0 to 2.0.0.0
/// - Version 0.5.0.0 of the file *does not* exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// -- The resulting assembly returned should be 2.0.0.0.
/// Rationale:
/// There's no way for the resolve algorithm to determine that the file reference corresponds
/// to a particular AssemblyName. Because of this, there's no way to determine that we want to
/// promote from 0.5.0.0 to 2.0.0.0. In this case, just use the assembly name that was passed in.
/// </summary>
[Fact]
public void LowVersionDoesntExist()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"C:\MyComponents\v0.5\UnifyMe.dll")
};
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='0.0.0.0-2.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.AssemblyFiles = assemblyFiles;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
Assert.Equal(t.ResolvedFiles[0].ItemSpec, assemblyFiles[0].ItemSpec);
// Cleanup.
File.Delete(appConfigFile);
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Collections;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Encoders;
namespace Org.BouncyCastle.Asn1.X9
{
/**
* table of the current named curves defined in X.962 EC-DSA.
*/
public sealed class X962NamedCurves
{
private X962NamedCurves()
{
}
internal class Prime192v1Holder
: X9ECParametersHolder
{
private Prime192v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime192v1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("ffffffffffffffffffffffff99def836146bc9b1b4d22831", 16);
BigInteger h = BigInteger.One;
ECCurve cFp192v1 = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"),
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16),
new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16),
n, h);
return new X9ECParameters(
cFp192v1,
cFp192v1.DecodePoint(
Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")),
n, h,
Hex.Decode("3045AE6FC8422f64ED579528D38120EAE12196D5"));
}
}
internal class Prime192v2Holder
: X9ECParametersHolder
{
private Prime192v2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime192v2Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("fffffffffffffffffffffffe5fb1a724dc80418648d8dd31", 16);
BigInteger h = BigInteger.One;
ECCurve cFp192v2 = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"),
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16),
new BigInteger("cc22d6dfb95c6b25e49c0d6364a4e5980c393aa21668d953", 16),
n, h);
return new X9ECParameters(
cFp192v2,
cFp192v2.DecodePoint(
Hex.Decode("03eea2bae7e1497842f2de7769cfe9c989c072ad696f48034a")),
n, h,
Hex.Decode("31a92ee2029fd10d901b113e990710f0d21ac6b6"));
}
}
internal class Prime192v3Holder
: X9ECParametersHolder
{
private Prime192v3Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime192v3Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("ffffffffffffffffffffffff7a62d031c83f4294f640ec13", 16);
BigInteger h = BigInteger.One;
ECCurve cFp192v3 = new FpCurve(
new BigInteger("6277101735386680763835789423207666416083908700390324961279"),
new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16),
new BigInteger("22123dc2395a05caa7423daeccc94760a7d462256bd56916", 16),
n, h);
return new X9ECParameters(
cFp192v3,
cFp192v3.DecodePoint(
Hex.Decode("027d29778100c65a1da1783716588dce2b8b4aee8e228f1896")),
n, h,
Hex.Decode("c469684435deb378c4b65ca9591e2a5763059a2e"));
}
}
internal class Prime239v1Holder
: X9ECParametersHolder
{
private Prime239v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime239v1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("7fffffffffffffffffffffff7fffff9e5e9a9f5d9071fbd1522688909d0b", 16);
BigInteger h = BigInteger.One;
ECCurve cFp239v1 = new FpCurve(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),
new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16),
n, h);
return new X9ECParameters(
cFp239v1,
cFp239v1.DecodePoint(
Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")),
n, h,
Hex.Decode("e43bb460f0b80cc0c0b075798e948060f8321b7d"));
}
}
internal class Prime239v2Holder
: X9ECParametersHolder
{
private Prime239v2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime239v2Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("7fffffffffffffffffffffff800000cfa7e8594377d414c03821bc582063", 16);
BigInteger h = BigInteger.One;
ECCurve cFp239v2 = new FpCurve(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),
new BigInteger("617fab6832576cbbfed50d99f0249c3fee58b94ba0038c7ae84c8c832f2c", 16),
n, h);
return new X9ECParameters(
cFp239v2,
cFp239v2.DecodePoint(
Hex.Decode("0238af09d98727705120c921bb5e9e26296a3cdcf2f35757a0eafd87b830e7")),
n, h,
Hex.Decode("e8b4011604095303ca3b8099982be09fcb9ae616"));
}
}
internal class Prime239v3Holder
: X9ECParametersHolder
{
private Prime239v3Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime239v3Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("7fffffffffffffffffffffff7fffff975deb41b3a6057c3c432146526551", 16);
BigInteger h = BigInteger.One;
ECCurve cFp239v3 = new FpCurve(
new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),
new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),
new BigInteger("255705fa2a306654b1f4cb03d6a750a30c250102d4988717d9ba15ab6d3e", 16),
n, h);
return new X9ECParameters(
cFp239v3,
cFp239v3.DecodePoint(
Hex.Decode("036768ae8e18bb92cfcf005c949aa2c6d94853d0e660bbf854b1c9505fe95a")),
n, h,
Hex.Decode("7d7374168ffe3471b60a857686a19475d3bfa2ff"));
}
}
internal class Prime256v1Holder
: X9ECParametersHolder
{
private Prime256v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Prime256v1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", 16);
BigInteger h = BigInteger.One;
ECCurve cFp256v1 = new FpCurve(
new BigInteger("115792089210356248762697446949407573530086143415290314195533631308867097853951"),
new BigInteger("ffffffff00000001000000000000000000000000fffffffffffffffffffffffc", 16),
new BigInteger("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", 16),
n, h);
return new X9ECParameters(
cFp256v1,
cFp256v1.DecodePoint(
Hex.Decode("036b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296")),
n, h,
Hex.Decode("c49d360886e704936a6678e1139d26b7819f7e90"));
}
}
/*
* F2m Curves
*/
internal class C2pnb163v1Holder
: X9ECParametersHolder
{
private C2pnb163v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb163v1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("0400000000000000000001E60FC8821CC74DAEAFC1", 16);
BigInteger h = BigInteger.Two;
ECCurve c2m163v1 = new F2mCurve(
163,
1, 2, 8,
new BigInteger("072546B5435234A422E0789675F432C89435DE5242", 16),
new BigInteger("00C9517D06D5240D3CFF38C74B20B6CD4D6F9DD4D9", 16),
n, h);
return new X9ECParameters(
c2m163v1,
c2m163v1.DecodePoint(
Hex.Decode("0307AF69989546103D79329FCC3D74880F33BBE803CB")),
n, h,
Hex.Decode("D2C0FB15760860DEF1EEF4D696E6768756151754"));
}
}
internal class C2pnb163v2Holder
: X9ECParametersHolder
{
private C2pnb163v2Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb163v2Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("03FFFFFFFFFFFFFFFFFFFDF64DE1151ADBB78F10A7", 16);
BigInteger h = BigInteger.Two;
ECCurve c2m163v2 = new F2mCurve(
163,
1, 2, 8,
new BigInteger("0108B39E77C4B108BED981ED0E890E117C511CF072", 16),
new BigInteger("0667ACEB38AF4E488C407433FFAE4F1C811638DF20", 16),
n, h);
return new X9ECParameters(
c2m163v2,
c2m163v2.DecodePoint(
Hex.Decode("030024266E4EB5106D0A964D92C4860E2671DB9B6CC5")),
n, h,
null);
}
}
internal class C2pnb163v3Holder
: X9ECParametersHolder
{
private C2pnb163v3Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb163v3Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("03FFFFFFFFFFFFFFFFFFFE1AEE140F110AFF961309", 16);
BigInteger h = BigInteger.Two;
ECCurve c2m163v3 = new F2mCurve(
163,
1, 2, 8,
new BigInteger("07A526C63D3E25A256A007699F5447E32AE456B50E", 16),
new BigInteger("03F7061798EB99E238FD6F1BF95B48FEEB4854252B", 16),
n, h);
return new X9ECParameters(
c2m163v3,
c2m163v3.DecodePoint(Hex.Decode("0202F9F87B7C574D0BDECF8A22E6524775F98CDEBDCB")),
n, h,
null);
}
}
internal class C2pnb176w1Holder
: X9ECParametersHolder
{
private C2pnb176w1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb176w1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("010092537397ECA4F6145799D62B0A19CE06FE26AD", 16);
BigInteger h = BigInteger.ValueOf(0xFF6E);
ECCurve c2m176w1 = new F2mCurve(
176,
1, 2, 43,
new BigInteger("00E4E6DB2995065C407D9D39B8D0967B96704BA8E9C90B", 16),
new BigInteger("005DDA470ABE6414DE8EC133AE28E9BBD7FCEC0AE0FFF2", 16),
n, h);
return new X9ECParameters(
c2m176w1,
c2m176w1.DecodePoint(
Hex.Decode("038D16C2866798B600F9F08BB4A8E860F3298CE04A5798")),
n, h,
null);
}
}
internal class C2tnb191v1Holder
: X9ECParametersHolder
{
private C2tnb191v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb191v1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("40000000000000000000000004A20E90C39067C893BBB9A5", 16);
BigInteger h = BigInteger.Two;
ECCurve c2m191v1 = new F2mCurve(
191,
9,
new BigInteger("2866537B676752636A68F56554E12640276B649EF7526267", 16),
new BigInteger("2E45EF571F00786F67B0081B9495A3D95462F5DE0AA185EC", 16),
n, h);
return new X9ECParameters(
c2m191v1,
c2m191v1.DecodePoint(
Hex.Decode("0236B3DAF8A23206F9C4F299D7B21A9C369137F2C84AE1AA0D")),
n, h,
Hex.Decode("4E13CA542744D696E67687561517552F279A8C84"));
}
}
internal class C2tnb191v2Holder
: X9ECParametersHolder
{
private C2tnb191v2Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb191v2Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("20000000000000000000000050508CB89F652824E06B8173", 16);
BigInteger h = BigInteger.ValueOf(4);
ECCurve c2m191v2 = new F2mCurve(
191,
9,
new BigInteger("401028774D7777C7B7666D1366EA432071274F89FF01E718", 16),
new BigInteger("0620048D28BCBD03B6249C99182B7C8CD19700C362C46A01", 16),
n, h);
return new X9ECParameters(
c2m191v2,
c2m191v2.DecodePoint(
Hex.Decode("023809B2B7CC1B28CC5A87926AAD83FD28789E81E2C9E3BF10")),
n, h,
null);
}
}
internal class C2tnb191v3Holder
: X9ECParametersHolder
{
private C2tnb191v3Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb191v3Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("155555555555555555555555610C0B196812BFB6288A3EA3", 16);
BigInteger h = BigInteger.ValueOf(6);
ECCurve c2m191v3 = new F2mCurve(
191,
9,
new BigInteger("6C01074756099122221056911C77D77E77A777E7E7E77FCB", 16),
new BigInteger("71FE1AF926CF847989EFEF8DB459F66394D90F32AD3F15E8", 16),
n, h);
return new X9ECParameters(
c2m191v3,
c2m191v3.DecodePoint(
Hex.Decode("03375D4CE24FDE434489DE8746E71786015009E66E38A926DD")),
n, h,
null);
}
}
internal class C2pnb208w1Holder
: X9ECParametersHolder
{
private C2pnb208w1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb208w1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("0101BAF95C9723C57B6C21DA2EFF2D5ED588BDD5717E212F9D", 16);
BigInteger h = BigInteger.ValueOf(0xFE48);
ECCurve c2m208w1 = new F2mCurve(
208,
1, 2, 83,
new BigInteger("0", 16),
new BigInteger("00C8619ED45A62E6212E1160349E2BFA844439FAFC2A3FD1638F9E", 16),
n, h);
return new X9ECParameters(
c2m208w1,
c2m208w1.DecodePoint(
Hex.Decode("0289FDFBE4ABE193DF9559ECF07AC0CE78554E2784EB8C1ED1A57A")),
n, h,
null);
}
}
internal class C2tnb239v1Holder
: X9ECParametersHolder
{
private C2tnb239v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb239v1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("2000000000000000000000000000000F4D42FFE1492A4993F1CAD666E447", 16);
BigInteger h = BigInteger.ValueOf(4);
ECCurve c2m239v1 = new F2mCurve(
239,
36,
new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16),
new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16),
n, h);
return new X9ECParameters(
c2m239v1,
c2m239v1.DecodePoint(
Hex.Decode("0257927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D")),
n, h,
null);
}
}
internal class C2tnb239v2Holder
: X9ECParametersHolder
{
private C2tnb239v2Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb239v2Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("1555555555555555555555555555553C6F2885259C31E3FCDF154624522D", 16);
BigInteger h = BigInteger.ValueOf(6);
ECCurve c2m239v2 = new F2mCurve(
239,
36,
new BigInteger("4230017757A767FAE42398569B746325D45313AF0766266479B75654E65F", 16),
new BigInteger("5037EA654196CFF0CD82B2C14A2FCF2E3FF8775285B545722F03EACDB74B", 16),
n, h);
return new X9ECParameters(
c2m239v2,
c2m239v2.DecodePoint(
Hex.Decode("0228F9D04E900069C8DC47A08534FE76D2B900B7D7EF31F5709F200C4CA205")),
n, h,
null);
}
}
internal class C2tnb239v3Holder
: X9ECParametersHolder
{
private C2tnb239v3Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb239v3Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("0CCCCCCCCCCCCCCCCCCCCCCCCCCCCCAC4912D2D9DF903EF9888B8A0E4CFF", 16);
BigInteger h = BigInteger.ValueOf(10);
ECCurve c2m239v3 = new F2mCurve(
239,
36,
new BigInteger("01238774666A67766D6676F778E676B66999176666E687666D8766C66A9F", 16),
new BigInteger("6A941977BA9F6A435199ACFC51067ED587F519C5ECB541B8E44111DE1D40", 16),
n, h);
return new X9ECParameters(
c2m239v3,
c2m239v3.DecodePoint(
Hex.Decode("0370F6E9D04D289C4E89913CE3530BFDE903977D42B146D539BF1BDE4E9C92")),
n, h,
null);
}
}
internal class C2pnb272w1Holder
: X9ECParametersHolder
{
private C2pnb272w1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb272w1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("0100FAF51354E0E39E4892DF6E319C72C8161603FA45AA7B998A167B8F1E629521", 16);
BigInteger h = BigInteger.ValueOf(0xFF06);
ECCurve c2m272w1 = new F2mCurve(
272,
1, 3, 56,
new BigInteger("0091A091F03B5FBA4AB2CCF49C4EDD220FB028712D42BE752B2C40094DBACDB586FB20", 16),
new BigInteger("7167EFC92BB2E3CE7C8AAAFF34E12A9C557003D7C73A6FAF003F99F6CC8482E540F7", 16),
n, h);
return new X9ECParameters(
c2m272w1,
c2m272w1.DecodePoint(
Hex.Decode("026108BABB2CEEBCF787058A056CBE0CFE622D7723A289E08A07AE13EF0D10D171DD8D")),
n, h,
null);
}
}
internal class C2pnb304w1Holder
: X9ECParametersHolder
{
private C2pnb304w1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb304w1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("0101D556572AABAC800101D556572AABAC8001022D5C91DD173F8FB561DA6899164443051D", 16);
BigInteger h = BigInteger.ValueOf(0xFE2E);
ECCurve c2m304w1 = new F2mCurve(
304,
1, 2, 11,
new BigInteger("00FD0D693149A118F651E6DCE6802085377E5F882D1B510B44160074C1288078365A0396C8E681", 16),
new BigInteger("00BDDB97E555A50A908E43B01C798EA5DAA6788F1EA2794EFCF57166B8C14039601E55827340BE", 16),
n, h);
return new X9ECParameters(
c2m304w1,
c2m304w1.DecodePoint(
Hex.Decode("02197B07845E9BE2D96ADB0F5F3C7F2CFFBD7A3EB8B6FEC35C7FD67F26DDF6285A644F740A2614")),
n, h,
null);
}
}
internal class C2tnb359v1Holder
: X9ECParametersHolder
{
private C2tnb359v1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb359v1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("01AF286BCA1AF286BCA1AF286BCA1AF286BCA1AF286BC9FB8F6B85C556892C20A7EB964FE7719E74F490758D3B", 16);
BigInteger h = BigInteger.ValueOf(0x4C);
ECCurve c2m359v1 = new F2mCurve(
359,
68,
new BigInteger("5667676A654B20754F356EA92017D946567C46675556F19556A04616B567D223A5E05656FB549016A96656A557", 16),
new BigInteger("2472E2D0197C49363F1FE7F5B6DB075D52B6947D135D8CA445805D39BC345626089687742B6329E70680231988", 16),
n, h);
return new X9ECParameters(
c2m359v1,
c2m359v1.DecodePoint(
Hex.Decode("033C258EF3047767E7EDE0F1FDAA79DAEE3841366A132E163ACED4ED2401DF9C6BDCDE98E8E707C07A2239B1B097")),
n, h,
null);
}
}
internal class C2pnb368w1Holder
: X9ECParametersHolder
{
private C2pnb368w1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2pnb368w1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("010090512DA9AF72B08349D98A5DD4C7B0532ECA51CE03E2D10F3B7AC579BD87E909AE40A6F131E9CFCE5BD967", 16);
BigInteger h = BigInteger.ValueOf(0xFF70);
ECCurve c2m368w1 = new F2mCurve(
368,
1, 2, 85,
new BigInteger("00E0D2EE25095206F5E2A4F9ED229F1F256E79A0E2B455970D8D0D865BD94778C576D62F0AB7519CCD2A1A906AE30D", 16),
new BigInteger("00FC1217D4320A90452C760A58EDCD30C8DD069B3C34453837A34ED50CB54917E1C2112D84D164F444F8F74786046A", 16),
n, h);
return new X9ECParameters(
c2m368w1,
c2m368w1.DecodePoint(
Hex.Decode("021085E2755381DCCCE3C1557AFA10C2F0C0C2825646C5B34A394CBCFA8BC16B22E7E789E927BE216F02E1FB136A5F")),
n, h,
null);
}
}
internal class C2tnb431r1Holder
: X9ECParametersHolder
{
private C2tnb431r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new C2tnb431r1Holder();
protected override X9ECParameters CreateParameters()
{
BigInteger n = new BigInteger("0340340340340340340340340340340340340340340340340340340323C313FAB50589703B5EC68D3587FEC60D161CC149C1AD4A91", 16);
BigInteger h = BigInteger.ValueOf(0x2760);
ECCurve c2m431r1 = new F2mCurve(
431,
120,
new BigInteger("1A827EF00DD6FC0E234CAF046C6A5D8A85395B236CC4AD2CF32A0CADBDC9DDF620B0EB9906D0957F6C6FEACD615468DF104DE296CD8F", 16),
new BigInteger("10D9B4A3D9047D8B154359ABFB1B7F5485B04CEB868237DDC9DEDA982A679A5A919B626D4E50A8DD731B107A9962381FB5D807BF2618", 16),
n, h);
return new X9ECParameters(
c2m431r1,
c2m431r1.DecodePoint(
Hex.Decode("02120FC05D3C67A99DE161D2F4092622FECA701BE4F50F4758714E8A87BBF2A658EF8C21E7C5EFE965361F6C2999C0C247B0DBD70CE6B7")),
n, h,
null);
}
}
private static readonly IDictionary objIds = Platform.CreateHashtable();
private static readonly IDictionary curves = Platform.CreateHashtable();
private static readonly IDictionary names = Platform.CreateHashtable();
private static void DefineCurve(
string name,
DerObjectIdentifier oid,
X9ECParametersHolder holder)
{
objIds.Add(Platform.ToLowerInvariant(name), oid);
names.Add(oid, name);
curves.Add(oid, holder);
}
static X962NamedCurves()
{
DefineCurve("prime192v1", X9ObjectIdentifiers.Prime192v1, Prime192v1Holder.Instance);
DefineCurve("prime192v2", X9ObjectIdentifiers.Prime192v2, Prime192v2Holder.Instance);
DefineCurve("prime192v3", X9ObjectIdentifiers.Prime192v3, Prime192v3Holder.Instance);
DefineCurve("prime239v1", X9ObjectIdentifiers.Prime239v1, Prime239v1Holder.Instance);
DefineCurve("prime239v2", X9ObjectIdentifiers.Prime239v2, Prime239v2Holder.Instance);
DefineCurve("prime239v3", X9ObjectIdentifiers.Prime239v3, Prime239v3Holder.Instance);
DefineCurve("prime256v1", X9ObjectIdentifiers.Prime256v1, Prime256v1Holder.Instance);
DefineCurve("c2pnb163v1", X9ObjectIdentifiers.C2Pnb163v1, C2pnb163v1Holder.Instance);
DefineCurve("c2pnb163v2", X9ObjectIdentifiers.C2Pnb163v2, C2pnb163v2Holder.Instance);
DefineCurve("c2pnb163v3", X9ObjectIdentifiers.C2Pnb163v3, C2pnb163v3Holder.Instance);
DefineCurve("c2pnb176w1", X9ObjectIdentifiers.C2Pnb176w1, C2pnb176w1Holder.Instance);
DefineCurve("c2tnb191v1", X9ObjectIdentifiers.C2Tnb191v1, C2tnb191v1Holder.Instance);
DefineCurve("c2tnb191v2", X9ObjectIdentifiers.C2Tnb191v2, C2tnb191v2Holder.Instance);
DefineCurve("c2tnb191v3", X9ObjectIdentifiers.C2Tnb191v3, C2tnb191v3Holder.Instance);
DefineCurve("c2pnb208w1", X9ObjectIdentifiers.C2Pnb208w1, C2pnb208w1Holder.Instance);
DefineCurve("c2tnb239v1", X9ObjectIdentifiers.C2Tnb239v1, C2tnb239v1Holder.Instance);
DefineCurve("c2tnb239v2", X9ObjectIdentifiers.C2Tnb239v2, C2tnb239v2Holder.Instance);
DefineCurve("c2tnb239v3", X9ObjectIdentifiers.C2Tnb239v3, C2tnb239v3Holder.Instance);
DefineCurve("c2pnb272w1", X9ObjectIdentifiers.C2Pnb272w1, C2pnb272w1Holder.Instance);
DefineCurve("c2pnb304w1", X9ObjectIdentifiers.C2Pnb304w1, C2pnb304w1Holder.Instance);
DefineCurve("c2tnb359v1", X9ObjectIdentifiers.C2Tnb359v1, C2tnb359v1Holder.Instance);
DefineCurve("c2pnb368w1", X9ObjectIdentifiers.C2Pnb368w1, C2pnb368w1Holder.Instance);
DefineCurve("c2tnb431r1", X9ObjectIdentifiers.C2Tnb431r1, C2tnb431r1Holder.Instance);
}
public static X9ECParameters GetByName(
string name)
{
DerObjectIdentifier oid = GetOid(name);
return oid == null ? null : GetByOid(oid);
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters GetByOid(
DerObjectIdentifier oid)
{
X9ECParametersHolder holder = (X9ECParametersHolder)curves[oid];
return holder == null ? null : holder.Parameters;
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DerObjectIdentifier GetOid(
string name)
{
return (DerObjectIdentifier)objIds[Platform.ToLowerInvariant(name)];
}
/**
* return the named curve name represented by the given object identifier.
*/
public static string GetName(
DerObjectIdentifier oid)
{
return (string)names[oid];
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static IEnumerable Names
{
get { return new EnumerableProxy(names.Values); }
}
}
}
#endif
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using ASC.Data.Storage.Configuration;
namespace ASC.Data.Storage
{
///<summary>
/// Interface for working with files
///</summary>
public interface IDataStore
{
IQuotaController QuotaController { get; set; }
TimeSpan GetExpire(string domain);
///<summary>
/// Get absolute Uri for html links to handler
///</summary>
///<param name="path"></param>
///<returns></returns>
Uri GetUri(string path);
///<summary>
/// Get absolute Uri for html links to handler
///</summary>
///<param name="domain"></param>
///<param name="path"></param>
///<returns></returns>
Uri GetUri(string domain, string path);
/// <summary>
/// Get absolute Uri for html links to handler
/// </summary>
/// <param name="domain"></param>
/// <param name="path"></param>
/// <param name="expire"></param>
/// <param name="headers"></param>
/// <returns></returns>
Uri GetPreSignedUri(string domain, string path, TimeSpan expire, IEnumerable<string> headers);
///<summary>
/// Supporting generate uri to the file
///</summary>
///<returns></returns>
bool IsSupportInternalUri { get; }
/// <summary>
/// Get absolute Uri for html links
/// </summary>
/// <param name="domain"></param>
/// <param name="path"></param>
/// <param name="expire"></param>
/// <param name="headers"></param>
/// <returns></returns>
Uri GetInternalUri(string domain, string path, TimeSpan expire, IEnumerable<string> headers);
///<summary>
/// A stream of read-only. In the case of the C3 stream NetworkStream general, and with him we have to work
/// Very carefully as a Jedi cutter groin lightsaber.
///</summary>
///<param name="domain"></param>
///<param name="path"></param>
///<returns></returns>
Stream GetReadStream(string domain, string path);
///<summary>
/// A stream of read-only. In the case of the C3 stream NetworkStream general, and with him we have to work
/// Very carefully as a Jedi cutter groin lightsaber.
///</summary>
///<param name="domain"></param>
///<param name="path"></param>
///<returns></returns>
Stream GetReadStream(string domain, string path, int offset);
Task<Stream> GetReadStreamAsync(string domain, string path, int offset);
///<summary>
/// Saves the contents of the stream in the repository.
///</ Summary>
/// <param Name="domain"> </param>
/// <param Name="path"> </param>
/// <param Name="stream"> flow. Is read from the current position! Desirable to set to 0 when the transmission MemoryStream instance </param>
/// <returns> </Returns>
Uri Save(string domain, string path, Stream stream);
/// <summary>
/// Saves the contents of the stream in the repository.
/// </summary>
/// <param name="domain"></param>
/// <param name="path"></param>
/// <param name="stream"></param>
/// <param name="acl"></param>
/// <returns></returns>
Uri Save(string domain, string path, Stream stream, ACL acl);
/// <summary>
/// Saves the contents of the stream in the repository.
/// </summary>
/// <param name="domain"></param>
/// <param name="path"></param>
/// <param name="stream"></param>
/// <param name="attachmentFileName"></param>
/// <returns></returns>
Uri Save(string domain, string path, Stream stream, string attachmentFileName);
/// <summary>
/// Saves the contents of the stream in the repository.
/// </summary>
/// <param name="domain"></param>
/// <param name="path"></param>
/// <param name="stream"></param>
/// <param name="contentType"></param>
/// <param name="contentDisposition"></param>
/// <returns></returns>
Uri Save(string domain, string path, Stream stream, string contentType, string contentDisposition);
/// <summary>
/// Saves the contents of the stream in the repository.
/// </summary>
/// <param name="domain"></param>
/// <param name="path"></param>
/// <param name="stream"></param>
/// <param name="contentEncoding"></param>
/// <param name="cacheDays"></param>
/// <returns></returns>
Uri Save(string domain, string path, Stream stream, string contentEncoding, int cacheDays);
string InitiateChunkedUpload(string domain, string path);
string UploadChunk(string domain, string path, string uploadId, Stream stream, long defaultChunkSize, int chunkNumber, long chunkLength);
Uri FinalizeChunkedUpload(string domain, string path, string uploadId, Dictionary<int, string> eTags);
void AbortChunkedUpload(string domain, string path, string uploadId);
bool IsSupportChunking { get; }
bool IsSupportedPreSignedUri { get; }
///<summary>
/// Deletes file
///</summary>
///<param name="domain"></param>
///<param name="path"></param>
void Delete(string domain, string path);
///<summary>
/// Deletes file by mask
///</summary>
///<param name="domain"></param>
///<param name="folderPath"></param>
///<param name="pattern">Wildcard mask (*.png)</param>
///<param name="recursive"></param>
void DeleteFiles(string domain, string folderPath, string pattern, bool recursive);
///<summary>
/// Deletes files
///</summary>
///<param name="domain"></param>
///<param name="listPaths"></param>
void DeleteFiles(string domain, List<string> paths);
///<summary>
/// Deletes file by last modified date
///</summary>
///<param name="domain"></param>
///<param name="folderPath"></param>
///<param name="fromDate"></param>
///<param name="toDate"></param>
void DeleteFiles(string domain, string folderPath, DateTime fromDate, DateTime toDate);
///<summary>
/// Moves the contents of one directory to another. s3 for a very expensive procedure.
///</summary>
///<param name="srcdomain"></param>
///<param name="srcdir"></param>
///<param name="newdomain"></param>
///<param name="newdir"></param>
void MoveDirectory(string srcdomain, string srcdir, string newdomain, string newdir);
///<summary>
/// Moves file
///</summary>
///<param name="srcdomain"></param>
///<param name="srcpath"></param>
///<param name="newdomain"></param>
///<param name="newpath"></param>
///<returns></returns>
Uri Move(string srcdomain, string srcpath, string newdomain, string newpath, bool quotaCheckFileSize = true);
///<summary>
/// Saves the file in the temp. In fact, almost no different from the usual Save except that generates the file name itself. An inconvenient thing.
///</summary>
///<param name="domain"></param>
///<param name="assignedPath"></param>
///<param name="stream"></param>
///<returns></returns>
Uri SaveTemp(string domain, out string assignedPath, Stream stream);
/// <summary>
/// Returns a list of links to all subfolders
/// </summary>
/// <param name="domain"></param>
/// <param name="path"></param>
/// <param name="recursive">iterate subdirectories or not</param>
/// <returns></returns>
string[] ListDirectoriesRelative(string domain, string path, bool recursive);
///<summary>
/// Returns a list of links to all files
///</summary>
///<param name="domain"></param>
///<param name="path"></param>
///<param name="pattern">Wildcard mask (*. jpg for example)</param>
///<param name="recursive">iterate subdirectories or not</param>
///<returns></returns>
Uri[] ListFiles(string domain, string path, string pattern, bool recursive);
///<summary>
/// Returns a list of relative paths for all files
///</summary>
///<param name="domain"></param>
///<param name="path"></param>
///<param name="pattern">Wildcard mask (*. jpg for example)</param>
///<param name="recursive">iterate subdirectories or not</param>
///<returns></returns>
string[] ListFilesRelative(string domain, string path, string pattern, bool recursive);
///<summary>
/// Checks whether a file exists. On s3 it took long time.
///</summary>
///<param name="domain"></param>
///<param name="path"></param>
///<returns></returns>
bool IsFile(string domain, string path);
Task<bool> IsFileAsync(string domain, string path);
///<summary>
/// Checks whether a directory exists. On s3 it took long time.
///</summary>
///<param name="domain"></param>
///<param name="path"></param>
///<returns></returns>
bool IsDirectory(string domain, string path);
void DeleteDirectory(string domain, string path);
long GetFileSize(string domain, string path);
Task<long> GetFileSizeAsync(string domain, string path);
long GetDirectorySize(string domain, string path);
long ResetQuota(string domain);
long GetUsedQuota(string domain);
Uri Copy(string srcdomain, string path, string newdomain, string newpath);
void CopyDirectory(string srcdomain, string dir, string newdomain, string newdir);
//Then there are restarted methods without domain. functionally identical to the top
#pragma warning disable 1591
Stream GetReadStream(string path);
Uri Save(string path, Stream stream, string attachmentFileName);
Uri Save(string path, Stream stream);
void Delete(string path);
void DeleteFiles(string folderPath, string pattern, bool recursive);
Uri Move(string srcpath, string newdomain, string newpath);
Uri SaveTemp(out string assignedPath, Stream stream);
string[] ListDirectoriesRelative(string path, bool recursive);
Uri[] ListFiles(string path, string pattern, bool recursive);
bool IsFile(string path);
bool IsDirectory(string path);
void DeleteDirectory(string path);
long GetFileSize(string path);
long GetDirectorySize(string path);
Uri Copy(string path, string newdomain, string newpath);
void CopyDirectory(string dir, string newdomain, string newdir);
#pragma warning restore 1591
IDataStore Configure(IDictionary<string, string> props);
IDataStore SetQuotaController(IQuotaController controller);
string SavePrivate(string domain, string path, Stream stream, DateTime expires);
void DeleteExpired(string domain, string path, TimeSpan oldThreshold);
string GetUploadForm(string domain, string directoryPath, string redirectTo, long maxUploadSize,
string contentType, string contentDisposition, string submitLabel);
string GetUploadedUrl(string domain, string directoryPath);
string GetUploadUrl();
string GetPostParams(string domain, string directoryPath, long maxUploadSize, string contentType,
string contentDisposition);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using NUnit.Framework;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using Microsoft.Build.UnitTests;
namespace Microsoft.Build.UnitTests.OM.OrcasCompatibility
{
/// <summary>
/// Test Fixture Class for the v9 Object Model Public Interface Compatibility Tests for the BuildTask Class.
/// </summary>
[TestFixture]
public sealed class BuildTask_Tests
{
#region Common Helpers
/// <summary>
/// Basic Project Contents with a Target 't' that contains 1 BuildTask 'Task' where
/// the BuildTask contains no parameters.
/// </summary>
private string ProjectContentsWithOneTask = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task />
</Target>
</Project>
");
/// <summary>
/// Engine that is used through out test class
/// </summary>
private Engine engine;
/// <summary>
/// Project that is used through out test class
/// </summary>
private Project project;
/// <summary>
/// MockLogger that is used through out test class
/// </summary>
private MockLogger logger;
/// <summary>
/// Creates the engine and parent object. Also registers the mock logger.
/// </summary>
[SetUp()]
public void Initialize()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
engine = new Engine();
engine.DefaultToolsVersion = "4.0";
project = new Project(engine);
logger = new MockLogger();
project.ParentEngine.RegisterLogger(logger);
}
/// <summary>
/// Unloads projects and un-registers logger.
/// </summary>
[TearDown()]
public void Cleanup()
{
engine.UnloadProject(project);
engine.UnloadAllProjects();
engine.UnregisterAllLoggers();
ObjectModelHelpers.DeleteTempProjectDirectory();
}
#endregion
#region Condition Tests
/// <summary>
/// Tests BuildTask.Condition Get simple/basic case
/// </summary>
[Test]
public void ConditionGetSimple()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition=""'a' == 'b'"" >
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals("'a' == 'b'", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Get when Condition is an empty string
/// </summary>
[Test]
public void ConditionGetEmptyString()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition="""" >
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals(String.Empty, task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Get when condition contains special characters
/// </summary>
[Test]
public void ConditionGetSpecialCharacters()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition=""%24%40%3b%5c%25"" >
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals("%24%40%3b%5c%25", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Get from an imported project
/// </summary>
[Test]
public void ConditionGetFromImportedProject()
{
string importProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t2' >
<t2.Task Condition=""'a' == 'b'"" >
</t2.Task>
</Target>
</Project>
");
Project p = GetProjectThatImportsAnotherProject(importProjectContents, null);
BuildTask task = GetSpecificBuildTask(p, "t2", "t2.Task");
Assertion.AssertEquals("'a' == 'b'", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set when no previous exists
/// </summary>
[Test]
public void ConditionSetWhenNoPreviousConditionExists()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = "'t' == 'f'";
Assertion.AssertEquals("'t' == 'f'", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set when an existing condition exists, changing the condition
/// </summary>
[Test]
public void ConditionSetOverExistingCondition()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition=""'a' == 'b'"" >
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = "'c' == 'd'";
Assertion.AssertEquals("'c' == 'd'", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set to an empty string
/// </summary>
[Test]
public void ConditionSetToEmtpyString()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = String.Empty;
Assertion.AssertEquals(String.Empty, task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set to null
/// </summary>
[Test]
public void ConditionSetToNull()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = null;
Assertion.AssertEquals(String.Empty, task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set to Special Characters
/// </summary>
[Test]
public void ConditionSetToSpecialCharacters()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = "%24%40%3b%5c%25";
Assertion.AssertEquals("%24%40%3b%5c%25", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set on an Imported Project
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void ConditionSetOnImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t3", "t3.Task3");
task.Condition = "true";
}
/// <summary>
/// Tests BuildTask.Condition Set, save to disk and verify
/// </summary>
[Test]
public void ConditionSaveProjectAfterSet()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = "'a' == 'b'";
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition=""'a' == 'b'"" />
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
#endregion
#region ContinueOnError Tests
/// <summary>
/// Tests BuildTask.ContinueOnError Get for all cases that would return true
/// </summary>
[Test]
public void ContinueOnErrorGetTrue()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task1 ContinueOnError='true' />
<Task2 ContinueOnError='True' />
<Task3 ContinueOnError='TRUE' />
<Task4 ContinueOnError='on' />
<Task5 ContinueOnError='yes' />
<Task6 ContinueOnError='!false' />
<Task7 ContinueOnError='!off' />
<Task8 ContinueOnError='!no' />
</Target>
</Project>
");
project.LoadXml(projectContents);
List<bool> continueOnErrorResults = GetListOfContinueOnErrorResultsFromSpecificProject(project);
Assertion.AssertEquals(true, continueOnErrorResults.TrueForAll(delegate(bool b) { return b; }));
}
/// <summary>
/// Tests BuildTask.ContinueOnError Get for all cases that would return false
/// </summary>
[Test]
public void ContinueOnErrorGetFalse()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task1 ContinueOnError='false' />
<Task2 ContinueOnError='False' />
<Task3 ContinueOnError='FALSE' />
<Task4 ContinueOnError='off' />
<Task5 ContinueOnError='no' />
<Task6 ContinueOnError='!true' />
<Task7 ContinueOnError='!on' />
<Task8 ContinueOnError='!yes' />
</Target>
</Project>
");
project.LoadXml(projectContents);
List<bool> continueOnErrorResults = GetListOfContinueOnErrorResultsFromSpecificProject(project);
Assertion.AssertEquals(true, continueOnErrorResults.TrueForAll(delegate(bool b) { return !b; }));
}
/// <summary>
/// Tests BuildTask.ContinueOnError Get when value is an empty string
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ContinueOnErrorGetEmptyString()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task ContinueOnError='' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError.ToString();
}
/// <summary>
/// Tests BuildTask.ContinueOnError Get when value is something that won't return true or false - invalid
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ContinueOnErrorGetInvalid()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task ContinueOnError='a' />
</Target>
</Project>
"));
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError.ToString();
}
/// <summary>
/// Tests BuildTask.ContinueOnError Get of a BuildTask from an imported Project
/// </summary>
[Test]
public void ContinueOnErrorGetFromImportedProject()
{
string importProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t2' >
<t2.Task ContinueOnError='true' />
</Target>
</Project>
");
Project p = GetProjectThatImportsAnotherProject(importProjectContents, null);
BuildTask task = GetSpecificBuildTask(p, "t2", "t2.Task");
Assertion.AssertEquals(true, task.ContinueOnError);
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set when no previous ContinueOnError value exists
/// </summary>
[Test]
public void ContinueOnErrorSetWhenNoContinueOnErrorExists()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError = true;
Assertion.AssertEquals(true, task.ContinueOnError);
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set when a ContinueOnError value exists (basically changing from true to false)
/// </summary>
[Test]
public void ContinueOnErrorSetWhenContinueOnErrorExists()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task ContinueOnError='true' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError = false;
Assertion.AssertEquals(false, task.ContinueOnError);
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set to true
/// </summary>
[Test]
public void ContinueOnErrorSetToTrue()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError = true;
Assertion.AssertEquals(true, task.ContinueOnError);
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set to false
/// </summary>
[Test]
public void ContinueOnErrorSetToFalse()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError = false;
Assertion.AssertEquals(false, task.ContinueOnError);
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set on an imported project
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void ContinueOnErrorSetOnImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t2", "t2.Task2");
task.ContinueOnError = true;
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set, then save to disk and verify
/// </summary>
[Test]
public void ContinueOnErrorSaveProjectAfterSet()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError = true;
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task ContinueOnError='true'/>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
#endregion
#region HostObject Tests
/// <summary>
/// Tests BuildTask.HostObject simple set and get with only one BuildTask
/// </summary>
[Test]
public void HostObjectSetGetOneTask()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t'>
<Message Text='t.message' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Message");
MockHostObject hostObject = new MockHostObject();
task.HostObject = hostObject;
Assertion.AssertSame(task.HostObject.ToString(), hostObject.ToString());
}
/// <summary>
/// Tests BuildTask.HostObject Set/Get with several BuildTasks
/// </summary>
[Test]
public void HostObjectSetGetMultipleTasks()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t'>
<Message Text='t.message' />
<MyTask />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task1 = GetSpecificBuildTask(project, "t", "Message");
BuildTask task2 = GetSpecificBuildTask(project, "t", "MyTask");
MockHostObject hostObject1 = new MockHostObject();
MockHostObject hostObject2 = new MockHostObject();
task1.HostObject = hostObject1;
task2.HostObject = hostObject2;
Assertion.AssertSame(task1.HostObject.ToString(), hostObject1.ToString());
Assertion.AssertSame(task2.HostObject.ToString(), hostObject2.ToString());
}
/// <summary>
/// Tests BuildTask.HostObject Get before the Object Reference is set to an instance of an object
/// </summary>
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void HostObjectGetBeforeObjectReferenceSet()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t'>
<Message Text='t.message' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Message");
task.HostObject.ToString();
}
#endregion
#region Name Tests
/// <summary>
/// Tests BuildTask.Name get when only one BuildTask exists
/// </summary>
[Test]
public void NameWithOneBuildTask()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='value' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals("Task", task.Name);
}
/// <summary>
/// Tests BuildTask.Name get when several BuildTasks exist within the same target
/// </summary>
[Test]
public void NameWithSeveralBuildTasksInSameTarget()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task1 parameter='value' />
<Task2 parameter='value' />
<Task3 parameter='value' />
</Target>
</Project>
");
project.LoadXml(projectContents);
Assertion.AssertEquals("Task1", GetSpecificBuildTask(project, "t", "Task1").Name);
Assertion.AssertEquals("Task2", GetSpecificBuildTask(project, "t", "Task2").Name);
Assertion.AssertEquals("Task3", GetSpecificBuildTask(project, "t", "Task3").Name);
}
/// <summary>
/// Tests BuildTask.Name get when several BuildTasks exist within different targets
/// </summary>
[Test]
public void NameWithSeveralBuildTasksInDifferentTargets()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t1' >
<t1.Task1 parameter='value' />
</Target>
<Target Name='t2' >
<t2.Task1 parameter='value' />
</Target>
<Target Name='t3' >
<t3.Task2 parameter='value' />
</Target>
</Project>
");
project.LoadXml(projectContents);
Assertion.AssertEquals("t1.Task1", GetSpecificBuildTask(project, "t1", "t1.Task1").Name);
Assertion.AssertEquals("t2.Task1", GetSpecificBuildTask(project, "t2", "t2.Task1").Name);
Assertion.AssertEquals("t3.Task2", GetSpecificBuildTask(project, "t3", "t3.Task2").Name);
}
/// <summary>
/// Tests BuildTask.Name get when BuildTask comes from an imported Project
/// </summary>
[Test]
public void NameOfBuildTaskFromImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
Assertion.AssertEquals("t3.Task3", GetSpecificBuildTask(p, "t3", "t3.Task3").Name);
}
/// <summary>
/// Tests BuildTask.Name get when BuildTask was just created
/// </summary>
[Test]
public void NameOfBuildTaskOfANewlyCreatedBuildTask()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t1' />
</Project>
");
project.LoadXml(projectContents);
Target t = GetSpecificTargetFromProject(project, "t1", false);
BuildTask task = t.AddNewTask("Task");
task.SetParameterValue("parameter", "value");
Assertion.AssertEquals("Task", GetSpecificBuildTask(project, "t1", "Task").Name);
}
#endregion
#region Type Tests
/// <summary>
/// Tests BuildTask.Type when Task class exists (Message)
/// </summary>
[Test]
public void TypeTaskExists()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t'>
<Message Text='t.message' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Message");
Assertion.AssertEquals(0, String.Compare(task.Type.ToString(), "Microsoft.Build.Tasks.Message"));
}
/// <summary>
/// Tests BuildTask.Type when Task class doesn't exists (MyFooTask)
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void TypeTaskNotExists()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t'>
<MyFooTask />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "MyFooTask");
Type t = task.Type;
}
/// <summary>
/// Tests BuildTask.Type when BuildTask is null
/// </summary>
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void TypeTaskIsNull()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = null;
Type t = task.Type;
}
#endregion
#region AddOutputItem/AddOutputProperty Tests
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by adding a new OutputItem/OutputProperty when none exist
/// </summary>
[Test]
public void AddOutputItemPropertyWhenNoOutputItemsPropertyExist()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem("ip", "in");
task.AddOutputProperty("pp", "pn");
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='ip' ItemName='in' />
<Output TaskParameter='pp' PropertyName='pn' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by adding a new OutputItem/OutputProperty when several exist
/// </summary>
[Test]
public void AddOutputItemPropertyWhenOutputItemsPropertiesExist()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='ip1' ItemName='in1' />
<Output TaskParameter='ip2' ItemName='in2' />
<Output TaskParameter='ip3' ItemName='in3' />
<Output TaskParameter='pp1' PropertyName='pn1' />
<Output TaskParameter='pp2' PropertyName='pn2' />
<Output TaskParameter='pp3' PropertyName='pn3' />
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem("ip4", "in4");
task.AddOutputProperty("pp4", "pn4");
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='ip1' ItemName='in1' />
<Output TaskParameter='ip2' ItemName='in2' />
<Output TaskParameter='ip3' ItemName='in3' />
<Output TaskParameter='pp1' PropertyName='pn1' />
<Output TaskParameter='pp2' PropertyName='pn2' />
<Output TaskParameter='pp3' PropertyName='pn3' />
<Output TaskParameter='ip4' ItemName='in4' />
<Output TaskParameter='pp4' PropertyName='pn4' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by adding a new OutputItem/OutputProperty
/// with the same values as an existing OutputItem/OutputProperty
/// </summary>
[Test]
public void AddOutputItemPropertyWithSameValuesAsExistingOutputItemProperty()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='ip' ItemName='in' />
<Output TaskParameter='pp' PropertyName='pn' />
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem("ip", "in");
task.AddOutputProperty("pp", "pn");
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='ip' ItemName='in' />
<Output TaskParameter='pp' PropertyName='pn' />
<Output TaskParameter='ip' ItemName='in' />
<Output TaskParameter='pp' PropertyName='pn' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by adding Empty Strings for the taskParameter and itemName/propertyName
/// </summary>
[Test]
public void AddOutputItemPropertyWithEmptyStrings()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem(String.Empty, String.Empty);
task.AddOutputProperty(String.Empty, String.Empty);
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='' ItemName='' />
<Output TaskParameter='' PropertyName='' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by adding nulls for the taskParameter and itemName/propertyName
/// </summary>
[Test]
public void AddOutputItemPropertyWithNulls()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem(null, null);
task.AddOutputProperty(null, null);
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='' ItemName='' />
<Output TaskParameter='' PropertyName='' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by passing in Special characters into the taskParameter and itemName/propertyName
/// </summary>
[Test]
public void AddOutputItemPropertyWithSpecialCharacters()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem("%24%40%3b%5c%25", "%24%40%3b%5c%25");
task.AddOutputProperty("%24%40%3b%5c%25", "%24%40%3b%5c%25");
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='%24%40%3b%5c%25' ItemName='%24%40%3b%5c%25' />
<Output TaskParameter='%24%40%3b%5c%25' PropertyName='%24%40%3b%5c%25' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem by attempting to add an OutputItem to an imported Project
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void AddOutputItemToImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t2", "t2.Task2");
task.AddOutputItem("p", "n");
}
/// <summary>
/// Tests BuildTask.AddOutputProperty by attempting to add an OutputProperty to an imported Project
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void AddOutputPropertyToImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t2", "t2.Task2");
task.AddOutputProperty("p", "n");
}
#endregion
#region Execute Tests
/// <summary>
/// Tests BuildTask.Execute basic case where expected to be true
/// </summary>
[Test]
public void ExecuteExpectedTrue()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t1'>
<Message Text='t1.message' />
</Target>
<Target Name='t2'>
<Message Text='t2.message' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t2", "Message");
Assertion.AssertEquals(0, String.Compare(task.Type.ToString(), "Microsoft.Build.Tasks.Message", StringComparison.OrdinalIgnoreCase));
Assertion.AssertEquals(true, task.Execute());
Assertion.AssertEquals(true, logger.FullLog.Contains("t2.message"));
Assertion.AssertEquals(false, logger.FullLog.Contains("t1.message"));
}
/// <summary>
/// Tests BuildTask.Execute where the BuildTask is null
/// </summary>
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void ExecuteOnNullBuildTask()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = null;
task.Execute();
}
/// <summary>
/// Tests BuildTask.Execute where the BuildTask doesn't do anything
/// </summary>
[Test]
public void ExecuteOnTaskThatDoesNothing()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals(false, task.Execute());
Assertion.AssertEquals(true, logger.FullLog.Contains("MSB4036"));
}
/// <summary>
/// Tests BuildTask.Execute where Task comes from an Imported Project
/// </summary>
[Test]
public void ExecuteFromImportedProject()
{
string importProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t' >
<Message Text='t.message' />
</Target>
</Project>
");
string parentProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Import Project='import.proj' />
</Project>
");
Project p = GetProjectThatImportsAnotherProject(importProjectContents, parentProjectContents);
BuildTask task = GetSpecificBuildTask(p, "t", "Message");
Assertion.AssertEquals(true, task.Execute());
}
#endregion
#region GetParameterNames Tests
/// <summary>
/// Tests BuildTask.GetParameterNames when only one parameter exists on the BuildTask
/// </summary>
[Test]
public void GetParameterNamesOnlyOneParameterExists()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='value'/>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
string[] parameters = task.GetParameterNames();
Assertion.AssertEquals(1, parameters.Length);
Assertion.AssertEquals("parameter", parameters[0]);
}
/// <summary>
/// Tests BuildTask.GetParameterNames when no parameters exist on the BuildTask
/// </summary>
[Test]
public void GetParameterNamesNoParametersExist()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task/>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
string[] parameters = task.GetParameterNames();
Assertion.AssertEquals(0, parameters.Length);
}
/// <summary>
/// Tests BuildTask.GetParameterNames when several parameters exist on the BuildTask
/// </summary>
[Test]
public void GetParameterNamesLotsOfParametersExist()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task p1='v1' p2='v2' p3='v3' p4='v4' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
string[] parameters = task.GetParameterNames();
Assertion.AssertEquals(4, parameters.Length);
Assertion.AssertEquals("p1", parameters[0]);
Assertion.AssertEquals("p2", parameters[1]);
Assertion.AssertEquals("p3", parameters[2]);
Assertion.AssertEquals("p4", parameters[3]);
}
#endregion
#region GetParameterValue Tests
/// <summary>
/// Tests BuildTask.GetParameterValue on one BuildTask
/// </summary>
[Test]
public void GetParameterValueOneBuildTaskWithOneParameter()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='value'/>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals("value", task.GetParameterValue("parameter"));
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value is special characters
/// </summary>
[Test]
public void GetParameterValueWhenSpecialCharacters()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='%24%40%3b%5c%25'/>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals("%24%40%3b%5c%25", task.GetParameterValue("parameter"));
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value is an empty string
/// </summary>
[Test]
public void GetParameterValueWhenEmtpyString()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals(String.Empty, task.GetParameterValue("parameter"));
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value is the Special Task Attribute 'Condition'
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void GetParameterValueWhenSpecialTaskAttributeCondition()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition='A' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.GetParameterValue("Condition");
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value is the Special Task Attribute 'ContinueOnError'
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void GetParameterValueWhenSpecialTaskAttributeContinueOnError()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task ContinueOnError='true' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.GetParameterValue("ContinueOnError");
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value is the Special Task Attribute 'xmlns'
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void GetParameterValueWhenSpecialTaskAttributexmlns()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task xmlns='msbuildnamespace' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.GetParameterValue("xmlns");
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value comes from an imported Project
/// </summary>
[Test]
public void GetParameterValueFromImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t3", "t3.Task3");
Assertion.AssertEquals("value", task.GetParameterValue("parameter"));
}
#endregion
#region SetParameterValue Tests
/// <summary>
/// Tests BuildTask.SetParameterValue on one BuildTask, simple case
/// </summary>
[Test]
public void SetParameterValueSimple()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("p", "v");
Assertion.AssertEquals("v", task.GetParameterValue("p"));
}
/// <summary>
/// Tests BuildTask.SetParameterValue to null
/// </summary>
[Test]
public void SetParameterValueToNull()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("p", null);
Assertion.AssertEquals(String.Empty, task.GetParameterValue("p"));
}
/// <summary>
/// Tests BuildTask.SetParameterValue to an Empty String
/// </summary>
[Test]
public void SetParameterValueToEmptyString()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("p", String.Empty);
Assertion.AssertEquals(String.Empty, task.GetParameterValue("p"));
}
/// <summary>
/// Tests BuildTask.SetParameterValue to special characters
/// </summary>
[Test]
public void SetParameterValueToSpecialCharacters()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("p", "%24%40%3b%5c%25");
}
/// <summary>
/// Tests BuildTask.SetParameterValue to Special Task Attribute Condition
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void SetParameterValueToSpecialTaskAttributeCondition()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("Condition", "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue to Special Task Attribute ContinueOnError
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void SetParameterValueToSpecialTaskAttributeContinueOnError()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("ContinueOnError", "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue to Special Task Attribute xmlns
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void SetParameterValueToSpecialTaskAttributexmlns()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("xmlns", "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue on a BuildTask from an Imported Project
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void SetParameterValueOnBuildTaskFromImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t3", "t3.Task3");
task.SetParameterValue("p", "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue on a BuildTask parameter that already exists
/// </summary>
[Test]
public void SetParameterValueOnAnExistingParameter()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='value'/>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("parameter", "new");
Assertion.AssertEquals("new", task.GetParameterValue("parameter"));
}
/// <summary>
/// Tests BuildTask.SetParameterValue, then save to disk and verify
/// </summary>
[Test]
public void SetParameterValueSaveProjectAfterSet()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("parameter", "value");
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='value'/>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.SetParameterValue by setting the parameter name to an empty string
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void SetParameterValueWithParameterNameSetToEmptyString()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue(String.Empty, "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue by setting the parameter name to null
/// </summary>
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void SetParameterValueWithParameterNameSetToNull()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue(null, "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue by setting the parameter name to special characters
/// </summary>
[Test]
[ExpectedException(typeof(XmlException))]
public void SetParameterValueWithParameterNameSetToSpecialCharacters()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("%24%40%3b%5c%25", "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue with the Treat Parameter Value As Literal set to true/false
/// </summary>
[Test]
public void SetParameterValueTreatParameterValueAsLiteral()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("p1", @"%*?@$();\", true);
task.SetParameterValue("p2", @"%*?@$();\", false);
Assertion.AssertEquals(@"%25%2a%3f%40%24%28%29%3b\", task.GetParameterValue("p1"));
Assertion.AssertEquals(@"%*?@$();\", task.GetParameterValue("p2"));
}
#endregion
#region Helpers
/// <summary>
/// Gets a list of all ContinueOnError results within your project
/// </summary>
/// <param name="p">Project</param>
/// <returns>List of bool results for all ContinueOnError BuildTasks within your project</returns>
private List<bool> GetListOfContinueOnErrorResultsFromSpecificProject(Project p)
{
List<bool> continueOnErrorResults = new List<bool>();
foreach (Target t in project.Targets)
{
foreach (BuildTask task in t)
{
continueOnErrorResults.Add(task.ContinueOnError);
}
}
return continueOnErrorResults;
}
/// <summary>
/// Gets the specified BuildTask from your specified Project and Target
/// </summary>
/// <param name="p">Project</param>
/// <param name="targetNameThatContainsBuildTask">Target that contains the BuildTask that you want</param>
/// <param name="buildTaskName">BuildTask name that you want</param>
/// <returns>The specified BuildTask</returns>
private BuildTask GetSpecificBuildTask(Project p, string targetNameThatContainsBuildTask, string buildTaskName)
{
foreach (Target t in p.Targets)
{
if (String.Equals(t.Name, targetNameThatContainsBuildTask, StringComparison.OrdinalIgnoreCase))
{
foreach (BuildTask task in t)
{
if (String.Equals(task.Name, buildTaskName, StringComparison.OrdinalIgnoreCase))
{
return task;
}
}
}
}
return null;
}
/// <summary>
/// Gets a specified Target from a Project
/// </summary>
/// <param name="p">Project</param>
/// <param name="nameOfTarget">Target name of the Target you want</param>
/// <param name="lastInstance">If you want the last instance of a target set to true</param>
/// <returns>Target requested. null if specific target isn't found</returns>
private Target GetSpecificTargetFromProject(Project p, string nameOfTarget, bool lastInstance)
{
Target target = null;
foreach (Target t in p.Targets)
{
if (String.Equals(t.Name, nameOfTarget, StringComparison.OrdinalIgnoreCase))
{
if (!lastInstance)
{
return t;
}
else
{
target = t;
}
}
}
return target;
}
/// <summary>
/// Saves a given Project to disk and compares what's saved to disk with expected contents. Assertion handled within
/// ObjectModelHelpers.CompareProjectContents.
/// </summary>
/// <param name="p">Project to save</param>
/// <param name="expectedProjectContents">The Project content that you expect</param>
private void SaveProjectToDiskAndCompareAgainstExpectedContents(Project p, string expectedProjectContents)
{
string savePath = Path.Combine(ObjectModelHelpers.TempProjectDir, "p.proj");
p.Save(savePath);
Engine e = new Engine();
Project savedProject = new Project(e);
savedProject.Load(savePath);
ObjectModelHelpers.CompareProjectContents(savedProject, expectedProjectContents);
ObjectModelHelpers.DeleteTempProjectDirectory();
}
/// <summary>
/// Gets a Project that imports another Project
/// </summary>
/// <param name="importProjectContents">Project Contents of the imported Project, to get default content, pass in an empty string</param>
/// <param name="parentProjectContents">Project Contents of the Parent Project, to get default content, pass in an empty string</param>
/// <returns>Project</returns>
private Project GetProjectThatImportsAnotherProject(string importProjectContents, string parentProjectContents)
{
if (String.IsNullOrEmpty(importProjectContents))
{
importProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t2' >
<t2.Task2 parameter='value' />
</Target>
<Target Name='t3' >
<t3.Task3 parameter='value' />
</Target>
</Project>
");
}
if (String.IsNullOrEmpty(parentProjectContents))
{
parentProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t1'>
<t1.Task1 parameter='value' />
</Target>
<Import Project='import.proj' />
</Project>
");
}
ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", importProjectContents);
ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", parentProjectContents);
return ObjectModelHelpers.LoadProjectFileInTempProjectDirectory("main.proj", null);
}
/// <summary>
/// Un-registers the existing logger and registers a new copy.
/// We will use this when we do multiple builds so that we can safely
/// assert on log messages for that particular build.
/// </summary>
private void ResetLogger()
{
engine.UnregisterAllLoggers();
logger = new MockLogger();
project.ParentEngine.RegisterLogger(logger);
}
/// <summary>
/// MyHostObject class for testing BuildTask HostObject
/// </summary>
internal class MockHostObject : ITaskHost
{
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace LinqToDB.DataProvider.DB2
{
using Data;
using Common;
using Extensions;
using Mapping;
using SchemaProvider;
using SqlProvider;
public class DB2DataProvider : DynamicDataProviderBase
{
public DB2DataProvider(string name, DB2Version version)
: base(name, null)
{
Version = version;
SqlProviderFlags.AcceptsTakeAsParameter = false;
SqlProviderFlags.AcceptsTakeAsParameterIfSkip = true;
SqlProviderFlags.IsDistinctOrderBySupported = false;
SqlProviderFlags.IsCommonTableExpressionsSupported = true;
SetCharFieldToType<char>("CHAR", (r, i) => DataTools.GetChar(r, i));
SetCharField("CHAR", (r,i) => r.GetString(i).TrimEnd(' '));
_sqlOptimizer = new DB2SqlOptimizer(SqlProviderFlags);
}
protected override void OnConnectionTypeCreated(Type connectionType)
{
DB2Types.ConnectionType = connectionType;
DB2Types.DB2Int64. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Int64", true);
DB2Types.DB2Int32. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Int32", true);
DB2Types.DB2Int16. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Int16", true);
DB2Types.DB2Decimal. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Decimal", true);
DB2Types.DB2DecimalFloat.Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2DecimalFloat", true);
DB2Types.DB2Real. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Real", true);
DB2Types.DB2Real370. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Real370", true);
DB2Types.DB2Double. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Double", true);
DB2Types.DB2String. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2String", true);
DB2Types.DB2Clob. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Clob", true);
DB2Types.DB2Binary. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Binary", true);
DB2Types.DB2Blob. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Blob", true);
DB2Types.DB2Date. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Date", true);
DB2Types.DB2Time. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Time", true);
DB2Types.DB2TimeStamp. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2TimeStamp", true);
DB2Types.DB2Xml = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2Xml", true);
DB2Types.DB2RowId. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2RowId", true);
DB2Types.DB2DateTime. Type = connectionType.AssemblyEx().GetType("IBM.Data.DB2Types.DB2DateTime", false);
SetProviderField(DB2Types.DB2Int64, typeof(Int64), "GetDB2Int64");
SetProviderField(DB2Types.DB2Int32, typeof(Int32), "GetDB2Int32");
SetProviderField(DB2Types.DB2Int16, typeof(Int16), "GetDB2Int16");
SetProviderField(DB2Types.DB2Decimal, typeof(Decimal), "GetDB2Decimal");
SetProviderField(DB2Types.DB2DecimalFloat, typeof(Decimal), "GetDB2DecimalFloat");
SetProviderField(DB2Types.DB2Real, typeof(Single), "GetDB2Real");
SetProviderField(DB2Types.DB2Real370, typeof(Single), "GetDB2Real370");
SetProviderField(DB2Types.DB2Double, typeof(Double), "GetDB2Double");
SetProviderField(DB2Types.DB2String, typeof(String), "GetDB2String");
SetProviderField(DB2Types.DB2Clob, typeof(String), "GetDB2Clob");
SetProviderField(DB2Types.DB2Binary, typeof(byte[]), "GetDB2Binary");
SetProviderField(DB2Types.DB2Blob, typeof(byte[]), "GetDB2Blob");
SetProviderField(DB2Types.DB2Date, typeof(DateTime), "GetDB2Date");
SetProviderField(DB2Types.DB2Time, typeof(TimeSpan), "GetDB2Time");
SetProviderField(DB2Types.DB2TimeStamp, typeof(DateTime), "GetDB2TimeStamp");
SetProviderField(DB2Types.DB2Xml, typeof(string), "GetDB2Xml");
SetProviderField(DB2Types.DB2RowId, typeof(byte[]), "GetDB2RowId");
MappingSchema.AddScalarType(DB2Types.DB2Int64, GetNullValue(DB2Types.DB2Int64), true, DataType.Int64);
MappingSchema.AddScalarType(DB2Types.DB2Int32, GetNullValue(DB2Types.DB2Int32), true, DataType.Int32);
MappingSchema.AddScalarType(DB2Types.DB2Int16, GetNullValue(DB2Types.DB2Int16), true, DataType.Int16);
MappingSchema.AddScalarType(DB2Types.DB2Decimal, GetNullValue(DB2Types.DB2Decimal), true, DataType.Decimal);
MappingSchema.AddScalarType(DB2Types.DB2DecimalFloat, GetNullValue(DB2Types.DB2DecimalFloat), true, DataType.Decimal);
MappingSchema.AddScalarType(DB2Types.DB2Real, GetNullValue(DB2Types.DB2Real), true, DataType.Single);
MappingSchema.AddScalarType(DB2Types.DB2Real370, GetNullValue(DB2Types.DB2Real370), true, DataType.Single);
MappingSchema.AddScalarType(DB2Types.DB2Double, GetNullValue(DB2Types.DB2Double), true, DataType.Double);
MappingSchema.AddScalarType(DB2Types.DB2String, GetNullValue(DB2Types.DB2String), true, DataType.NVarChar);
MappingSchema.AddScalarType(DB2Types.DB2Clob, GetNullValue(DB2Types.DB2Clob), true, DataType.NText);
MappingSchema.AddScalarType(DB2Types.DB2Binary, GetNullValue(DB2Types.DB2Binary), true, DataType.VarBinary);
MappingSchema.AddScalarType(DB2Types.DB2Blob, GetNullValue(DB2Types.DB2Blob), true, DataType.Blob);
MappingSchema.AddScalarType(DB2Types.DB2Date, GetNullValue(DB2Types.DB2Date), true, DataType.Date);
MappingSchema.AddScalarType(DB2Types.DB2Time, GetNullValue(DB2Types.DB2Time), true, DataType.Time);
MappingSchema.AddScalarType(DB2Types.DB2TimeStamp, GetNullValue(DB2Types.DB2TimeStamp), true, DataType.DateTime2);
MappingSchema.AddScalarType(DB2Types.DB2RowId, GetNullValue(DB2Types.DB2RowId), true, DataType.VarBinary);
MappingSchema.AddScalarType(DB2Types.DB2Xml, DB2Tools.IsCore ? null : GetNullValue(DB2Types.DB2Xml), true, DataType.Xml);
_setBlob = GetSetParameter(connectionType, "DB2Parameter", "DB2Type", "DB2Type", "Blob");
if (DB2Types.DB2DateTime.IsSupported)
{
SetProviderField(DB2Types.DB2DateTime, typeof(DateTime), "GetDB2DateTime");
MappingSchema.AddScalarType(DB2Types.DB2DateTime, GetNullValue(DB2Types.DB2DateTime), true, DataType.DateTime);
}
if (DataConnection.TraceSwitch.TraceInfo)
{
DataConnection.WriteTraceLine(
DataReaderType.AssemblyEx().FullName,
DataConnection.TraceSwitch.DisplayName);
DataConnection.WriteTraceLine(
DB2Types.DB2DateTime.IsSupported ? "DB2DateTime is supported." : "DB2DateTime is not supported.",
DataConnection.TraceSwitch.DisplayName);
}
DB2Tools.Initialized();
}
static object GetNullValue(Type type)
{
var getValue = Expression.Lambda<Func<object>>(Expression.Convert(Expression.Field(null, type, "Null"), typeof(object)));
return getValue.Compile()();
}
public override string ConnectionNamespace => DB2Tools.AssemblyName;
protected override string ConnectionTypeName => DB2Tools.AssemblyName + ".DB2Connection, " + DB2Tools.AssemblyName;
protected override string DataReaderTypeName => DB2Tools.AssemblyName + ".DB2DataReader, " + DB2Tools.AssemblyName;
#if !NETSTANDARD1_6 && !NETSTANDARD2_0
public override string DbFactoryProviderName => "IBM.Data.DB2";
#endif
public DB2Version Version { get; }
static class MappingSchemaInstance
{
public static readonly DB2LUWMappingSchema DB2LUWMappingSchema = new DB2LUWMappingSchema();
public static readonly DB2zOSMappingSchema DB2zOSMappingSchema = new DB2zOSMappingSchema();
}
public override MappingSchema MappingSchema
{
get
{
switch (Version)
{
case DB2Version.LUW : return MappingSchemaInstance.DB2LUWMappingSchema;
case DB2Version.zOS : return MappingSchemaInstance.DB2zOSMappingSchema;
}
return base.MappingSchema;
}
}
#if !NETSTANDARD1_6
public override ISchemaProvider GetSchemaProvider()
{
return Version == DB2Version.zOS ?
new DB2zOSSchemaProvider() :
new DB2LUWSchemaProvider();
}
#endif
public override ISqlBuilder CreateSqlBuilder()
{
return Version == DB2Version.zOS ?
new DB2zOSSqlBuilder(GetSqlOptimizer(), SqlProviderFlags, MappingSchema.ValueToSqlConverter) as ISqlBuilder:
new DB2LUWSqlBuilder(GetSqlOptimizer(), SqlProviderFlags, MappingSchema.ValueToSqlConverter);
}
readonly DB2SqlOptimizer _sqlOptimizer;
public override ISqlOptimizer GetSqlOptimizer()
{
return _sqlOptimizer;
}
public override void InitCommand(DataConnection dataConnection, CommandType commandType, string commandText, DataParameter[] parameters)
{
dataConnection.DisposeCommand();
base.InitCommand(dataConnection, commandType, commandText, parameters);
}
static Action<IDbDataParameter> _setBlob;
public override void SetParameter(IDbDataParameter parameter, string name, DbDataType dataType, object value)
{
if (value is sbyte sb)
{
value = (short)sb;
dataType = dataType.WithDataType(DataType.Int16);
}
else if (value is byte b)
{
value = (short)b;
dataType = dataType.WithDataType(DataType.Int16);
}
switch (dataType.DataType)
{
case DataType.UInt16 : dataType = dataType.WithDataType(DataType.Int32); break;
case DataType.UInt32 : dataType = dataType.WithDataType(DataType.Int64); break;
case DataType.UInt64 : dataType = dataType.WithDataType(DataType.Decimal); break;
case DataType.VarNumeric : dataType = dataType.WithDataType(DataType.Decimal); break;
case DataType.DateTime2 : dataType = dataType.WithDataType(DataType.DateTime); break;
case DataType.Char :
case DataType.VarChar :
case DataType.NChar :
case DataType.NVarChar :
{
if (value is Guid g) value = g.ToString();
else if (value is bool b) value = ConvertTo<char>.From(b);
break;
}
case DataType.Boolean :
case DataType.Int16 :
{
if (value is bool b)
{
value = b ? 1 : 0;
dataType = dataType.WithDataType(DataType.Int16);
}
break;
}
case DataType.Guid :
{
if (value is Guid g)
{
value = g.ToByteArray();
dataType = dataType.WithDataType(DataType.VarBinary);
}
if (value == null)
dataType = dataType.WithDataType(DataType.VarBinary);
break;
}
case DataType.Binary :
case DataType.VarBinary :
{
if (value is Guid g) value = g.ToByteArray();
else if (parameter.Size == 0 && value != null && value.GetType().Name == "DB2Binary")
{
dynamic v = value;
if (v.IsNull)
value = DBNull.Value;
}
break;
}
case DataType.Blob :
base.SetParameter(parameter, "@" + name, dataType, value);
_setBlob(parameter);
return;
}
base.SetParameter(parameter, "@" + name, dataType, value);
}
#region BulkCopy
DB2BulkCopy _bulkCopy;
public override BulkCopyRowsCopied BulkCopy<T>(ITable<T> table, BulkCopyOptions options, IEnumerable<T> source)
{
if (_bulkCopy == null)
_bulkCopy = new DB2BulkCopy(GetConnectionType());
return _bulkCopy.BulkCopy(
options.BulkCopyType == BulkCopyType.Default ? DB2Tools.DefaultBulkCopyType : options.BulkCopyType,
table,
options,
source);
}
#endregion
#region Merge
public override int Merge<T>(DataConnection dataConnection, Expression<Func<T,bool>> deletePredicate, bool delete, IEnumerable<T> source,
string tableName, string databaseName, string schemaName)
{
if (delete)
throw new LinqToDBException("DB2 MERGE statement does not support DELETE by source.");
return new DB2Merge().Merge(dataConnection, deletePredicate, delete, source, tableName, databaseName, schemaName);
}
public override Task<int> MergeAsync<T>(DataConnection dataConnection, Expression<Func<T,bool>> deletePredicate, bool delete, IEnumerable<T> source,
string tableName, string databaseName, string schemaName, CancellationToken token)
{
if (delete)
throw new LinqToDBException("DB2 MERGE statement does not support DELETE by source.");
return new DB2Merge().MergeAsync(dataConnection, deletePredicate, delete, source, tableName, databaseName, schemaName, token);
}
protected override BasicMergeBuilder<TTarget, TSource> GetMergeBuilder<TTarget, TSource>(
DataConnection connection,
IMergeable<TTarget, TSource> merge)
{
return new DB2MergeBuilder<TTarget, TSource>(connection, merge);
}
#endregion
}
}
| |
namespace NorthwindModelBuddy
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Objects.DataClasses;
using System.Linq;
using OpenRiaServices.DomainServices.Hosting;
using OpenRiaServices.DomainServices.Server;
using NorthwindModel;
// The MetadataTypeAttribute identifies CategoryBuddyMetadata as the class
// that carries additional metadata for the CategoryBuddy class.
[MetadataTypeAttribute(typeof(CategoryBuddy.CategoryBuddyMetadata))]
public partial class CategoryBuddy
{
// This class allows you to attach custom attributes to properties
// of the Category class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class CategoryBuddyMetadata
{
// Metadata classes are not meant to be instantiated.
private CategoryBuddyMetadata()
{
}
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public byte[] Picture { get; set; }
public EntityCollection<Product> Products { get; set; }
}
}
// The MetadataTypeAttribute identifies CustomerBuddyMetadata as the class
// that carries additional metadata for the CustomerBuddy class.
[MetadataTypeAttribute(typeof(CustomerBuddy.CustomerBuddyMetadata))]
public partial class CustomerBuddy
{
// This class allows you to attach custom attributes to properties
// of the Customer class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class CustomerBuddyMetadata
{
// Metadata classes are not meant to be instantiated.
private CustomerBuddyMetadata()
{
}
public string Address { get; set; }
public string City { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Country { get; set; }
public EntityCollection<CustomerDemographic> CustomerDemographics { get; set; }
public string CustomerID { get; set; }
public string Fax { get; set; }
public EntityCollection<Order> Orders { get; set; }
public string Phone { get; set; }
public string PostalCode { get; set; }
public string Region { get; set; }
}
}
// The MetadataTypeAttribute identifies CustomerDemographicBuddyMetadata as the class
// that carries additional metadata for the CustomerDemographicBuddy class.
[MetadataTypeAttribute(typeof(CustomerDemographicBuddy.CustomerDemographicBuddyMetadata))]
public partial class CustomerDemographicBuddy
{
// This class allows you to attach custom attributes to properties
// of the CustomerDemographic class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class CustomerDemographicBuddyMetadata
{
// Metadata classes are not meant to be instantiated.
private CustomerDemographicBuddyMetadata()
{
}
public string CustomerDesc { get; set; }
public EntityCollection<Customer> Customers { get; set; }
public string CustomerTypeID { get; set; }
}
}
// The MetadataTypeAttribute identifies EmployeeBuddyMetadata as the class
// that carries additional metadata for the EmployeeBuddy class.
[MetadataTypeAttribute(typeof(EmployeeBuddy.EmployeeBuddyMetadata))]
public partial class EmployeeBuddy
{
// This class allows you to attach custom attributes to properties
// of the Employee class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class EmployeeBuddyMetadata
{
// Metadata classes are not meant to be instantiated.
private EmployeeBuddyMetadata()
{
}
public string Address { get; set; }
public Nullable<DateTime> BirthDate { get; set; }
public string City { get; set; }
public string Country { get; set; }
public Employee Employee1 { get; set; }
public int EmployeeID { get; set; }
public EntityCollection<Employee> Employees1 { get; set; }
public string Extension { get; set; }
public string FirstName { get; set; }
public Nullable<DateTime> HireDate { get; set; }
public string HomePhone { get; set; }
public string LastName { get; set; }
public string Notes { get; set; }
public EntityCollection<Order> Orders { get; set; }
public byte[] Photo { get; set; }
public string PhotoPath { get; set; }
public string PostalCode { get; set; }
public string Region { get; set; }
public Nullable<int> ReportsTo { get; set; }
public EntityCollection<Territory> Territories { get; set; }
public string Title { get; set; }
public string TitleOfCourtesy { get; set; }
}
}
// The MetadataTypeAttribute identifies ShipperBuddyMetadata as the class
// that carries additional metadata for the ShipperBuddy class.
[MetadataTypeAttribute(typeof(ShipperBuddy.ShipperBuddyMetadata))]
public partial class ShipperBuddy
{
// This class allows you to attach custom attributes to properties
// of the Shipper class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class ShipperBuddyMetadata
{
// Metadata classes are not meant to be instantiated.
private ShipperBuddyMetadata()
{
}
public string CompanyName { get; set; }
public EntityCollection<Order> Orders { get; set; }
public string Phone { get; set; }
public int ShipperID { get; set; }
}
}
// The MetadataTypeAttribute identifies SupplierBuddyMetadata as the class
// that carries additional metadata for the SupplierBuddy class.
[MetadataTypeAttribute(typeof(SupplierBuddy.SupplierBuddyMetadata))]
public partial class SupplierBuddy
{
// This class allows you to attach custom attributes to properties
// of the Supplier class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class SupplierBuddyMetadata
{
// Metadata classes are not meant to be instantiated.
private SupplierBuddyMetadata()
{
}
public string Address { get; set; }
public string City { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Country { get; set; }
public string Fax { get; set; }
public string HomePage { get; set; }
public string Phone { get; set; }
public string PostalCode { get; set; }
public EntityCollection<Product> Products { get; set; }
public string Region { get; set; }
public int SupplierID { get; set; }
}
}
// The MetadataTypeAttribute identifies TerritoryBuddyMetadata as the class
// that carries additional metadata for the TerritoryBuddy class.
[MetadataTypeAttribute(typeof(TerritoryBuddy.TerritoryBuddyMetadata))]
public partial class TerritoryBuddy
{
// This class allows you to attach custom attributes to properties
// of the Territory class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class TerritoryBuddyMetadata
{
// Metadata classes are not meant to be instantiated.
private TerritoryBuddyMetadata()
{
}
public EntityCollection<Employee> Employees { get; set; }
public Region Region { get; set; }
public int RegionID { get; set; }
public string TerritoryDescription { get; set; }
public string TerritoryID { get; set; }
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Purpose: Resource annotation rules.
**
===========================================================*/
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.Win32;
using System.Diagnostics.Contracts;
namespace System.Runtime.Versioning
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
[Conditional("RESOURCE_ANNOTATION_WORK")]
public sealed class ResourceConsumptionAttribute : Attribute
{
private ResourceScope _consumptionScope;
private ResourceScope _resourceScope;
public ResourceConsumptionAttribute(ResourceScope resourceScope)
{
_resourceScope = resourceScope;
_consumptionScope = _resourceScope;
}
public ResourceConsumptionAttribute(ResourceScope resourceScope, ResourceScope consumptionScope)
{
_resourceScope = resourceScope;
_consumptionScope = consumptionScope;
}
public ResourceScope ResourceScope {
get { return _resourceScope; }
}
public ResourceScope ConsumptionScope {
get { return _consumptionScope; }
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
[Conditional("RESOURCE_ANNOTATION_WORK")]
public sealed class ResourceExposureAttribute : Attribute
{
private ResourceScope _resourceExposureLevel;
public ResourceExposureAttribute(ResourceScope exposureLevel)
{
_resourceExposureLevel = exposureLevel;
}
public ResourceScope ResourceExposureLevel {
get { return _resourceExposureLevel; }
}
}
// Default visibility is Public, which isn't specified in this enum.
// Public == the lack of Private or Assembly
// Does this actually work? Need to investigate that.
[Flags]
public enum ResourceScope
{
None = 0,
// Resource type
Machine = 0x1,
Process = 0x2,
AppDomain = 0x4,
Library = 0x8,
// Visibility
Private = 0x10, // Private to this one class.
Assembly = 0x20, // Assembly-level, like C#'s "internal"
}
[Flags]
internal enum SxSRequirements
{
None = 0,
AppDomainID = 0x1,
ProcessID = 0x2,
CLRInstanceID = 0x4, // for multiple CLR's within the process
AssemblyName = 0x8,
TypeName = 0x10
}
public static class VersioningHelper
{
// These depend on the exact values given to members of the ResourceScope enum.
private const ResourceScope ResTypeMask = ResourceScope.Machine | ResourceScope.Process | ResourceScope.AppDomain | ResourceScope.Library;
private const ResourceScope VisibilityMask = ResourceScope.Private | ResourceScope.Assembly;
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Process)]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int GetRuntimeId();
public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to)
{
return MakeVersionSafeName(name, from, to, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to, Type type)
{
ResourceScope fromResType = from & ResTypeMask;
ResourceScope toResType = to & ResTypeMask;
if (fromResType > toResType)
throw new ArgumentException(Environment.GetResourceString("Argument_ResourceScopeWrongDirection", fromResType, toResType), "from");
SxSRequirements requires = GetRequirements(to, from);
if ((requires & (SxSRequirements.AssemblyName | SxSRequirements.TypeName)) != 0 && type == null)
throw new ArgumentNullException("type", Environment.GetResourceString("ArgumentNull_TypeRequiredByResourceScope"));
// Add in process ID, CLR base address, and appdomain ID's. Also, use a character identifier
// to ensure that these can never accidentally overlap (ie, you create enough appdomains and your
// appdomain ID might equal your process ID).
StringBuilder safeName = new StringBuilder(name);
char separator = '_';
if ((requires & SxSRequirements.ProcessID) != 0) {
safeName.Append(separator);
safeName.Append('p');
safeName.Append(Win32Native.GetCurrentProcessId());
}
if ((requires & SxSRequirements.CLRInstanceID) != 0) {
String clrID = GetCLRInstanceString();
safeName.Append(separator);
safeName.Append('r');
safeName.Append(clrID);
}
if ((requires & SxSRequirements.AppDomainID) != 0) {
safeName.Append(separator);
safeName.Append("ad");
safeName.Append(AppDomain.CurrentDomain.Id);
}
if ((requires & SxSRequirements.TypeName) != 0) {
safeName.Append(separator);
safeName.Append(type.Name);
}
if ((requires & SxSRequirements.AssemblyName) != 0) {
safeName.Append(separator);
safeName.Append(type.Assembly.FullName);
}
return safeName.ToString();
}
private static String GetCLRInstanceString()
{
int id = GetRuntimeId();
return id.ToString(CultureInfo.InvariantCulture);
}
private static SxSRequirements GetRequirements(ResourceScope consumeAsScope, ResourceScope calleeScope)
{
SxSRequirements requires = SxSRequirements.None;
switch(calleeScope & ResTypeMask) {
case ResourceScope.Machine:
switch(consumeAsScope & ResTypeMask) {
case ResourceScope.Machine:
// No work
break;
case ResourceScope.Process:
requires |= SxSRequirements.ProcessID;
break;
case ResourceScope.AppDomain:
requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID | SxSRequirements.ProcessID;
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", consumeAsScope), "consumeAsScope");
}
break;
case ResourceScope.Process:
if ((consumeAsScope & ResourceScope.AppDomain) != 0)
requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID;
break;
case ResourceScope.AppDomain:
// No work
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", calleeScope), "calleeScope");
}
switch(calleeScope & VisibilityMask) {
case ResourceScope.None: // Public - implied
switch(consumeAsScope & VisibilityMask) {
case ResourceScope.None: // Public - implied
// No work
break;
case ResourceScope.Assembly:
requires |= SxSRequirements.AssemblyName;
break;
case ResourceScope.Private:
requires |= SxSRequirements.TypeName | SxSRequirements.AssemblyName;
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", consumeAsScope), "consumeAsScope");
}
break;
case ResourceScope.Assembly:
if ((consumeAsScope & ResourceScope.Private) != 0)
requires |= SxSRequirements.TypeName;
break;
case ResourceScope.Private:
// No work
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", calleeScope), "calleeScope");
}
if (consumeAsScope == calleeScope) {
Contract.Assert(requires == SxSRequirements.None, "Computed a strange set of required resource scoping. It's probably wrong.");
}
return requires;
}
}
}
| |
using System;
namespace SharpRT
{
static class Constants
{
/// <summary>
/// A positive real close to zero.
/// </summary>
public const float Epsilon = 1e-5f;
}
/// <summary>
/// An immutable three-dimensional vector.
/// </summary>
public struct Vector
{
private readonly float x;
private readonly float y;
private readonly float z;
/// <summary>
/// Gets the vector's x-coordinate.
/// </summary>
public float X { get { return x; } }
/// <summary>
/// Gets the vector's y-coordinate.
/// </summary>
public float Y { get { return y; } }
/// <summary>
/// Gets the vector's z-coordinate.
/// </summary>
public float Z { get { return z; } }
/// <summary>
/// Indexed access to vector components (zero-based).
/// </summary>
public float this[int t]
{
get
{
switch (t)
{
case 0: return X;
case 1: return Y;
case 2: return Z;
default: throw new ArgumentOutOfRangeException("Invalid component index: " + t);
}
}
}
/// <summary>
/// Constructs a new three-dimensional vector.
/// </summary>
public Vector(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
public static Vector operator +(Vector u, Vector v)
{
return new Vector(u.X + v.X, u.Y + v.Y, u.Z + v.Z);
}
public static Vector operator +(Vector u)
{
return new Vector(u.X, u.Y, u.Z);
}
public static Vector operator -(Vector u, Vector v)
{
return u + (-v);
}
public static Vector operator -(Vector u)
{
return new Vector(-u.X, -u.Y, -u.Z);
}
public static Vector operator *(Vector u, Vector v)
{
return new Vector(u.X * v.X, u.Y * v.Y, u.Z * v.Z);
}
public static Vector operator *(Vector u, float s)
{
return new Vector(u.X * s, u.Y * s, u.Z * s);
}
public static Vector operator *(float s, Vector u)
{
return u * s;
}
public static Vector operator /(Vector u, float s)
{
return u * (1.0f / s);
}
public static Vector operator /(float s, Vector u)
{
return u / s;
}
/// <summary>
/// Returns the length of a vector.
/// </summary>
public static float Length(Vector u)
{
return (float)Math.Sqrt(Dot(u, u));
}
/// <summary>
/// Normalizes a vector to unit length.
/// </summary>
public static Vector Normalize(Vector u)
{
var len = Length(u);
if (len != 0) return u / len;
else throw new InvalidOperationException("Vector has no direction");
}
/// <summary>
/// Returns the inclination of a vector.
/// </summary>
/// <remarks>
/// Vertical angle, zero on the xz-plane.
/// </remarks>
public static float Inclination(Vector u)
{
var len = Length(u);
if (len != 0) return (float)(Math.PI / 2 - Math.Acos(u.Y / len));
else throw new InvalidOperationException("Vector has no direction");
}
/// <summary>
/// Returns the azimuth of a vector.
/// </summary>
/// <remarks>
/// Horizontal angle, zero along the z-axis.
/// </remarks>
public static float Azimuth(Vector u)
{
var len = Length(u);
if (len != 0) return (float)Math.Atan2(u.Z, u.X);
else throw new InvalidOperationException("Vector has no direction");
}
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
public static float Dot(Vector u, Vector v)
{
return u.X * v.X + u.Y * v.Y + u.Z * v.Z;
}
/// <summary>
/// Returns the cross product of two vectors.
/// </summary>
public static Vector Cross(Vector u, Vector v)
{
return new Vector(u.Y * v.Z - u.Z * v.Y,
u.Z * v.X - u.X * v.Z,
u.X * v.Y - u.Y * v.X);
}
/// <summary>
/// Returns the length of this vector.
/// </summary>
public float Length()
{
return Length(this);
}
/// <summary>
/// Returns this vector, normalized.
/// </summary>
public Vector Normalize()
{
return Normalize(this);
}
/// <summary>
/// Returns the inclination of this vector.
/// </summary>
public float Inclination()
{
return Inclination(this);
}
/// <summary>
/// Returns the azimuth of this vector.
/// </summary>
public float Azimuth()
{
return Azimuth(this);
}
/// <summary>
/// Returns the dot product of this vector with another.
/// </summary>
public float Dot(Vector v)
{
return Dot(this, v);
}
/// <summary>
/// Returns the cross product of this vector with another.
/// </summary>
public Vector Cross(Vector v)
{
return Cross(this, v);
}
/// <summary>
/// Converts a vector into a point.
/// </summary>
/// <remarks>
/// This is meaningless mathematically.
/// </remarks>
public static Point ToPoint(Vector u)
{
return Point.Zero + u;
}
/// <summary>
/// Converts this vector into a point.
/// </summary>
public Point ToPoint()
{
return ToPoint(this);
}
/// <summary>
/// Returns a textual representation of this vector.
/// </summary>
public override string ToString()
{
return string.Format("[{0:G2}, {1:G2}, {2:G2}]", X, Y, Z);
}
/// <summary>
/// The vector with length zero.
/// </summary>
public static Vector Zero = new Vector(0, 0, 0);
}
/// <summary>
/// An immutable three-dimensional point.
/// </summary>
public struct Point
{
private readonly float x;
private readonly float y;
private readonly float z;
/// <summary>
/// Gets the point's x-coordinate.
/// </summary>
public float X { get { return x; } }
/// <summary>
/// Gets the point's y-coordinate.
/// </summary>
public float Y { get { return y; } }
/// <summary>
/// Gets the point's z-coordinate.
/// </summary>
public float Z { get { return z; } }
/// <summary>
/// Indexed access to point components (zero-based).
/// </summary>
public float this[int t]
{
get
{
switch (t)
{
case 0: return X;
case 1: return Y;
case 2: return Z;
default: throw new ArgumentOutOfRangeException("Invalid component index: " + t);
}
}
}
/// <summary>
/// Constructs a new three-dimensional point.
/// </summary>
public Point(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
public static Point operator +(Point p, Vector u)
{
return new Point(u.X + p.X, u.Y + p.Y, u.Z + p.Z);
}
public static Point operator -(Point p, Vector u)
{
return p + (-u);
}
public static Point operator +(Vector u, Point p)
{
return p + u;
}
public static Point operator +(Point u)
{
return new Point(u.X, u.Y, u.Z);
}
public static Vector operator -(Point u, Point v)
{
return new Vector(u.X - v.X, u.Y - v.Y, u.Z - v.Z);
}
/// <summary>
/// Converts a point into a vector.
/// </summary>
/// <remarks>
/// This is meaningless mathematically.
/// </remarks>
public static Vector ToVector(Point p)
{
return p - Point.Zero;
}
/// <summary>
/// Converts this point into a vector.
/// </summary>
public Vector ToVector()
{
return ToVector(this);
}
/// <summary>
/// Returns a textual representation of this point.
/// </summary>
public override string ToString()
{
return string.Format("[{0:G2}, {1:G2}, {2:G2}]", X, Y, Z);
}
/// <summary>
/// The point at the origin.
/// </summary>
public static Point Zero = new Point(0, 0, 0);
public static implicit operator Point(Embree.Vertex vertex)
{
return new Point(vertex.X, vertex.Y, vertex.Z);
}
public static implicit operator Embree.Vertex(Point point)
{
return new Embree.Vertex {
X = point.X,
Y = point.Y,
Z = point.Z
};
}
}
/// <summary>
/// An immutable ray, of unit length.
/// </summary>
public class Ray
{
private readonly Point origin;
private readonly Vector direction;
/// <summary>
/// Gets the ray's origin.
/// </summary>
public Point Origin { get { return origin; } }
/// <summary>
/// Gets the ray's (unit length) direction.
/// </summary>
public Vector Direction { get { return direction; } }
/// <summary>
/// Constructs a ray with an origin and a direction.
/// </summary>
public Ray(Point origin, Vector direction)
{
this.origin = origin;
this.direction = direction.Normalize();
}
/// <summary>
/// Returns the point at a given distance along the ray.
/// </summary>
public static Point PointAt(Ray ray, float distance)
{
return ray.Origin + ray.Direction * distance;
}
/// <summary>
/// Transforms a ray by a given matrix.
/// </summary>
public static Ray Transform(Ray ray, Matrix transform)
{
Point p1 = transform.Transform(ray.Origin);
Point p2 = transform.Transform(ray.Origin + ray.Direction);
return new Ray(p1, p2 - p1);
}
/// <summary>
/// Returns a point at a given distance along this ray.
/// </summary>
public Point PointAt(float distance)
{
return PointAt(this, distance);
}
/// <summary>
/// Transforms this ray by a given matrix.
/// </summary>
public Ray Transform(Matrix transform)
{
return Transform(this, transform);
}
public static Ray operator *(Matrix transform, Ray ray)
{
return Transform(ray, transform);
}
/// <summary>
/// Returns a textual representation of this ray.
/// </summary>
public override string ToString()
{
return string.Format("O={0}, D={1}", Origin, Direction);
}
}
/// <summary>
/// An immutable 3x4 transformation matrix.
/// </summary>
/// <remarks>
/// This matrix is laid out in column major order.
/// </remarks>
public class Matrix
{
private readonly Vector u;
private readonly Vector v;
private readonly Vector w;
private readonly Vector t;
/// <summary>
/// The first column (the x-axis of the basis).
/// </summary>
public Vector U { get { return u; } }
/// <summary>
/// The second column (the y-axis of the basis).
/// </summary>
public Vector V { get { return v; } }
/// <summary>
/// The third column (the z-axis of the basis).
/// </summary>
public Vector W { get { return w; } }
/// <summary>
/// The fourth column, corresponding to translation.
/// </summary>
public Vector T { get { return t; } }
/// <summary>
/// Indexed access to matrix columns (zero-based).
/// </summary>
public Vector this[int t]
{
get
{
switch (t)
{
case 0: return U;
case 1: return V;
case 2: return W;
case 3: return T;
default: throw new ArgumentOutOfRangeException("Invalid column index: " + t);
}
}
}
/// <summary>
/// Constructs a matrix from four column vectors.
/// </summary>
public Matrix(Vector u, Vector v, Vector w, Vector t = default(Vector))
{
this.u = u;
this.v = v;
this.w = w;
this.t = t;
}
/// <summary>
/// Creates a translation matrix.
/// </summary>
public static Matrix Translation(Vector vec)
{
return new Matrix(new Vector(1, 0, 0),
new Vector(0, 1, 0),
new Vector(0, 0, 1),
vec);
}
/// <summary>
/// Creates a translation matrix.
/// </summary>
/// <param name="vec">The point which was the origin.</param>
public static Matrix Translation(Point pt)
{
return new Matrix(new Vector(1, 0, 0),
new Vector(0, 1, 0),
new Vector(0, 0, 1),
pt.ToVector());
}
/// <summary>
/// Creates a uniform scaling matrix.
/// </summary>
public static Matrix Scaling(float scale)
{
return new Matrix(new Vector(scale, 0, 0),
new Vector(0, scale, 0),
new Vector(0, 0, scale),
Vector.Zero);
}
/// <summary>
/// Creates a possibly non-uniform scaling matrix.
/// </summary>
public static Matrix Scaling(Vector scale)
{
return new Matrix(new Vector(scale.X, 0, 0),
new Vector(0, scale.Y, 0),
new Vector(0, 0, scale.Z),
Vector.Zero);
}
/// <summary>
/// Creates a rotation matrix about the x-axis,
/// </summary>
public static Matrix RotationX(float pitch)
{
var c = (float)Math.Cos(pitch);
var s = (float)Math.Sin(pitch);
return new Matrix(new Vector(+1, +0, +0),
new Vector(+0, +c, -s),
new Vector(+0, +s, +c),
Vector.Zero);
}
/// <summary>
/// Creates a rotation matrix about the y-axis,
/// </summary>
public static Matrix RotationY(float yaw)
{
var c = (float)Math.Cos(yaw);
var s = (float)Math.Sin(yaw);
return new Matrix(new Vector(+c, +0, +s),
new Vector(+0, +1, +0),
new Vector(-s, +0, +c),
Vector.Zero);
}
/// <summary>
/// Creates a rotation matrix about the z-axis,
/// </summary>
public static Matrix RotationZ(float roll)
{
var c = (float)Math.Cos(roll);
var s = (float)Math.Sin(roll);
return new Matrix(new Vector(+c, -s, +0),
new Vector(+s, +c, +0),
new Vector(+0, +0, +1),
Vector.Zero);
}
/// <summary>
/// Creates a rotation matrix from three Euler angles.
/// </summary>
public static Matrix Rotation(float pitch, float yaw, float roll)
{
return RotationX(pitch) * RotationY(yaw) * RotationZ(roll);
}
/// <summary>
/// Combines the list of transformations matrices such that a vector
/// transformed by the resulting matrix would undergo each transform
/// in the order specified by the arguments.
/// </summary>
/// <remarks>
/// For an ordinary transformation matrix, the order should be:
///
/// - any scaling
/// - rotation(s)
/// - translation
/// </remarks>
public static Matrix Combine(params Matrix[] transformations)
{
var mat = Matrix.Identity;
foreach (Matrix transform in transformations)
mat = transform * mat;
return mat;
}
public static Matrix operator *(Matrix m1, Matrix m2)
{
var m00 = (m1.U.X * m2.U.X) + (m1.V.X * m2.U.Y) + (m1.W.X * m2.U.Z);
var m01 = (m1.U.X * m2.V.X) + (m1.V.X * m2.V.Y) + (m1.W.X * m2.V.Z);
var m02 = (m1.U.X * m2.W.X) + (m1.V.X * m2.W.Y) + (m1.W.X * m2.W.Z);
var m03 = (m1.U.X * m2.T.X) + (m1.V.X * m2.T.Y) + (m1.W.X * m2.T.Z) + m1.T.X;
var m10 = (m1.U.Y * m2.U.X) + (m1.V.Y * m2.U.Y) + (m1.W.Y * m2.U.Z);
var m11 = (m1.U.Y * m2.V.X) + (m1.V.Y * m2.V.Y) + (m1.W.Y * m2.V.Z);
var m12 = (m1.U.Y * m2.W.X) + (m1.V.Y * m2.W.Y) + (m1.W.Y * m2.W.Z);
var m13 = (m1.U.Y * m2.T.X) + (m1.V.Y * m2.T.Y) + (m1.W.Y * m2.T.Z) + m1.T.Y;
var m20 = (m1.U.Z * m2.U.X) + (m1.V.Z * m2.U.Y) + (m1.W.Z * m2.U.Z);
var m21 = (m1.U.Z * m2.V.X) + (m1.V.Z * m2.V.Y) + (m1.W.Z * m2.V.Z);
var m22 = (m1.U.Z * m2.W.X) + (m1.V.Z * m2.W.Y) + (m1.W.Z * m2.W.Z);
var m23 = (m1.U.Z * m2.T.X) + (m1.V.Z * m2.T.Y) + (m1.W.Z * m2.T.Z) + m1.T.Z;
return new Matrix(new Vector(m00, m10, m20),
new Vector(m01, m11, m21),
new Vector(m02, m12, m22),
new Vector(m03, m13, m23));
}
/// <summary>
/// Transforms a vector by a matrix.
/// </summary>
public static Vector Transform(Matrix mat, Vector vec)
{
return vec.X * mat.U + vec.Y * mat.V + vec.Z * mat.W;
}
/// <summary>
/// Transforms a point by a matrix.
/// </summary>
public static Point Transform(Matrix mat, Point pt)
{
return (pt.X * mat.U + pt.Y * mat.V + pt.Z * mat.W).ToPoint() + mat.T;
}
/// <summary>
/// Transforms a vector by this matrix.
/// </summary>
public Vector Transform(Vector vec)
{
return Transform(this, vec);
}
/// <summary>
/// Transforms a point by this matrix.
/// </summary>
public Point Transform(Point pt)
{
return Transform(this, pt);
}
public static Vector operator *(Matrix mat, Vector vec)
{
return Transform(mat, vec);
}
public static Point operator *(Matrix mat, Point pt)
{
return Transform(mat, pt);
}
/// <summary>
/// Returns the inverse of a matrix.
/// </summary>
public static Matrix Invert(Matrix mat)
{
// Work out determinant of the 3x3 submatrix
var det = mat.U.X * (mat.V.Y * mat.W.Z - mat.W.Y * mat.V.Z)
- mat.V.X * (mat.W.Z * mat.U.Y - mat.W.Y * mat.U.Z)
+ mat.W.X * (mat.U.Y * mat.V.Z - mat.V.Y * mat.U.Z);
if (Math.Abs(det) < 1e-10)
throw new ArgumentException("Matrix is not invertible");
// Compute inv(submatrix) = transpose(submatrix) / det
var inv_u = new Vector(mat.U.X, mat.V.X, mat.W.X) / det;
var inv_v = new Vector(mat.U.Y, mat.V.Y, mat.W.Y) / det;
var inv_w = new Vector(mat.U.Z, mat.V.Z, mat.W.Z) / det;
// Transform the translation column by this inverse matrix
var inv_t = -(mat.T.X * inv_u + mat.T.Y * inv_v + mat.T.Z * inv_w);
return new Matrix(inv_u, inv_v, inv_w, inv_t);
}
/// <summary>
/// Returns the "transpose" of a matrix, this is the
/// transpose of the 3x3 submatrix, no translation.
/// </summary>
/// <remarks>
/// In general, Transpose(Transpose(mat)) != mat.
/// </remarks>
private static Matrix Transpose(Matrix mat)
{
return new Matrix(new Vector(mat.U.X, mat.V.X, mat.W.X),
new Vector(mat.U.Y, mat.V.Y, mat.W.Y),
new Vector(mat.U.Z, mat.V.Z, mat.W.Z),
Vector.Zero);
}
/// <summary>
/// Returns the inverse transpose of this matrix,
/// for use in transformation of normal vectors.
/// </summary>
/// <remarks>
/// The resulting matrix always has no translation.
/// </remarks>
/// <remarks>
/// If the matrix is orthogonal (rotation only) then
/// this method returns the same matrix.
/// </remarks>
public static Matrix InverseTranspose(Matrix mat)
{
return Transpose(Invert(mat));
}
/// <summary>
/// Inverts this matrix.
/// </summary>
public Matrix Invert()
{
return Invert(this);
}
/// <summary>
/// Transposes this matrix.
/// </summary>
private Matrix Transpose()
{
return Transpose(this);
}
/// <summary>
/// Returns the inverse transpose of this matrix.
/// </summary>
public Matrix InverseTranspose()
{
return InverseTranspose(this);
}
/// <summary>
/// Returns the matrix as a column-major float array.
/// </summary>
public float[] ToArray()
{
return new float[] {
U.X, U.Y, U.Z,
V.X, V.Y, V.Z,
W.X, W.Y, W.Z,
T.X, T.Y, T.Z,
};
}
/// <summary>
/// Returns a textual representation of this matrix.
/// </summary>
public override string ToString()
{
return string.Format("[{0}, {1}, {2}, {3}]", U, V, W, T);
}
/// <summary>
/// Returns the 3x4 identity transformation matrix.
/// </summary>
public static Matrix Identity = new Matrix(new Vector(1, 0, 0),
new Vector(0, 1, 0),
new Vector(0, 0, 1),
new Vector(0, 0, 0));
}
}
| |
// Copyright (c) 2014-2016 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
using System;
using System.Collections.Generic;
using SharpNav.Collections;
using SharpNav.Geometry;
#if MONOGAME
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Vector2 = Microsoft.Xna.Framework.Vector2;
#elif OPENTK
using Vector3 = OpenTK.Vector3;
using Vector2 = OpenTK.Vector2;
#elif SHARPDX
using Vector3 = SharpDX.Vector3;
using Vector2 = SharpDX.Vector2;
#endif
namespace SharpNav.Pathfinding
{
/// <summary>
/// The MeshTile contains the map data for pathfinding
/// </summary>
public class NavTile : IEquatable<NavTile>
{
private NavPolyIdManager idManager;
private NavPolyId baseRef;
public NavTile(int x, int y, int layer, NavPolyIdManager manager, NavPolyId baseRef)
:this(new Vector2i(x, y), layer, manager, baseRef)
{
}
public NavTile(Vector2i location, int layer, NavPolyIdManager manager, NavPolyId baseRef)
{
this.Location = location;
this.Layer = layer;
this.idManager = manager;
this.baseRef = baseRef;
}
public Vector2i Location { get; private set; }
public int Layer { get; private set; }
/// <summary>
/// Gets or sets the counter describing modifications to the tile
/// </summary>
public int Salt { get; set; }
/// <summary>
/// Gets or sets the PolyMesh polygons
/// </summary>
public NavPoly[] Polys { get; set; }
public int PolyCount { get; set; }
/// <summary>
/// Gets or sets the PolyMesh vertices
/// </summary>
public Vector3[] Verts { get; set; }
/// <summary>
/// Gets or sets the PolyMeshDetail data
/// </summary>
public PolyMeshDetail.MeshData[] DetailMeshes { get; set; }
/// <summary>
/// Gets or sets the PolyMeshDetail vertices
/// </summary>
public Vector3[] DetailVerts { get; set; }
/// <summary>
/// Gets or sets the PolyMeshDetail triangles
/// </summary>
public PolyMeshDetail.TriangleData[] DetailTris { get; set; }
/// <summary>
/// Gets or sets the OffmeshConnections
/// </summary>
public OffMeshConnection[] OffMeshConnections { get; set; }
public int OffMeshConnectionCount { get; set; }
/// <summary>
/// Gets or sets the bounding volume tree
/// </summary>
public BVTree BVTree { get; set; }
public float BvQuantFactor { get; set; }
public int BvNodeCount { get; set; }
public BBox3 Bounds { get; set; }
public float WalkableClimb { get; set; }
/// <summary>
/// Allocate links for each of the tile's polygons' vertices
/// </summary>
public void ConnectIntLinks()
{
//Iterate through all the polygons
for (int i = 0; i < PolyCount; i++)
{
NavPoly p = Polys[i];
//Avoid Off-Mesh Connection polygons
if (p.PolyType == NavPolyType.OffMeshConnection)
continue;
//Build edge links
for (int j = p.VertCount - 1; j >= 0; j--)
{
//Skip hard and non-internal edges
if (p.Neis[j] == 0 || Link.IsExternal(p.Neis[j]))
continue;
NavPolyId id;
idManager.SetPolyIndex(ref baseRef, p.Neis[j] - 1, out id);
//Initialize a new link
Link link = new Link();
link.Reference = id;
link.Edge = j;
link.Side = BoundarySide.Internal;
link.BMin = link.BMax = 0;
p.Links.Add(link);
}
}
}
/// <summary>
/// Begin creating off-mesh links between the tile polygons.
/// </summary>
public void BaseOffMeshLinks()
{
//Base off-mesh connection start points
for (int i = 0; i < OffMeshConnectionCount; i++)
{
int con = i;
OffMeshConnection omc = OffMeshConnections[con];
Vector3 extents = new Vector3(omc.Radius, WalkableClimb, omc.Radius);
//Find polygon to connect to
Vector3 p = omc.Pos0;
Vector3 nearestPt = new Vector3();
NavPolyId reference = FindNearestPoly(p, extents, ref nearestPt);
if (reference == NavPolyId.Null)
continue;
//Do extra checks
if ((nearestPt.X - p.X) * (nearestPt.X - p.X) + (nearestPt.Z - p.Z) * (nearestPt.Z - p.Z) >
OffMeshConnections[con].Radius * OffMeshConnections[con].Radius)
continue;
NavPoly poly = this.Polys[omc.Poly];
//Make sure location is on current mesh
Verts[poly.Verts[0]] = nearestPt;
Link link = new Link();
link.Reference = reference;
link.Edge = 0;
link.Side = BoundarySide.Internal;
poly.Links.Add(link);
//Start end-point always conects back to off-mesh connection
int landPolyIdx = idManager.DecodePolyIndex(ref reference);
NavPolyId id;
idManager.SetPolyIndex(ref baseRef, OffMeshConnections[con].Poly, out id);
Link link2 = new Link();
link2.Reference = id;
link2.Edge = 0xff;
link2.Side = BoundarySide.Internal;
Polys[landPolyIdx].Links.Add(link2);
}
}
/// <summary>
/// Connect polygons from two different tiles.
/// </summary>
/// <param name="target">Target Tile</param>
/// <param name="side">Polygon edge</param>
public void ConnectExtLinks(NavTile target, BoundarySide side)
{
//Connect border links
for (int i = 0; i < PolyCount; i++)
{
int numPolyVerts = Polys[i].VertCount;
for (int j = 0; j < numPolyVerts; j++)
{
//Skip non-portal edges
if ((Polys[i].Neis[j] & Link.External) == 0)
continue;
BoundarySide dir = (BoundarySide)(Polys[i].Neis[j] & 0xff);
if (side != BoundarySide.Internal && dir != side)
continue;
//Create new links
Vector3 va = Verts[Polys[i].Verts[j]];
Vector3 vb = Verts[Polys[i].Verts[(j + 1) % numPolyVerts]];
List<NavPolyId> nei = new List<NavPolyId>(4);
List<float> neia = new List<float>(4 * 2);
target.FindConnectingPolys(va, vb, dir.GetOpposite(), nei, neia);
//Iterate through neighbors
for (int k = 0; k < nei.Count; k++)
{
Link link = new Link();
link.Reference = nei[k];
link.Edge = j;
link.Side = dir;
Polys[i].Links.Add(link);
//Compress portal limits to a value
if (dir == BoundarySide.PlusX || dir == BoundarySide.MinusX)
{
float tmin = (neia[k * 2 + 0] - va.Z) / (vb.Z - va.Z);
float tmax = (neia[k * 2 + 1] - va.Z) / (vb.Z - va.Z);
if (tmin > tmax)
{
float temp = tmin;
tmin = tmax;
tmax = temp;
}
link.BMin = (int)(MathHelper.Clamp(tmin, 0.0f, 1.0f) * 255.0f);
link.BMax = (int)(MathHelper.Clamp(tmax, 0.0f, 1.0f) * 255.0f);
}
else if (dir == BoundarySide.PlusZ || dir == BoundarySide.MinusZ)
{
float tmin = (neia[k * 2 + 0] - va.X) / (vb.X - va.X);
float tmax = (neia[k * 2 + 1] - va.X) / (vb.X - va.X);
if (tmin > tmax)
{
float temp = tmin;
tmin = tmax;
tmax = temp;
}
link.BMin = (int)(MathHelper.Clamp(tmin, 0.0f, 1.0f) * 255.0f);
link.BMax = (int)(MathHelper.Clamp(tmax, 0.0f, 1.0f) * 255.0f);
}
}
}
}
}
/// <summary>
/// Connect Off-Mesh links between polygons from two different tiles.
/// </summary>
/// <param name="target">Target Tile</param>
/// <param name="side">Polygon edge</param>
public void ConnectExtOffMeshLinks(NavTile target, BoundarySide side)
{
//Connect off-mesh links, specifically links which land from target tile to this tile
BoundarySide oppositeSide = side.GetOpposite();
//Iterate through all the off-mesh connections of target tile
for (int i = 0; i < target.OffMeshConnectionCount; i++)
{
OffMeshConnection targetCon = target.OffMeshConnections[i];
if (targetCon.Side != oppositeSide)
continue;
NavPoly targetPoly = target.Polys[targetCon.Poly];
//Skip off-mesh connections which start location could not be connected at all
if (targetPoly.Links.Count == 0)
continue;
Vector3 extents = new Vector3(targetCon.Radius, target.WalkableClimb, targetCon.Radius);
//Find polygon to connect to
Vector3 p = targetCon.Pos1;
Vector3 nearestPt = new Vector3();
NavPolyId reference = FindNearestPoly(p, extents, ref nearestPt);
if (reference == NavPolyId.Null)
continue;
//Further checks
if ((nearestPt.X - p.X) * (nearestPt.X - p.X) + (nearestPt.Z - p.Z) * (nearestPt.Z - p.Z) >
(targetCon.Radius * targetCon.Radius))
continue;
//Make sure the location is on the current mesh
target.Verts[targetPoly.Verts[1]] = nearestPt;
//Link off-mesh connection to target poly
Link link = new Link();
link.Reference = reference;
link.Edge = i;
link.Side = oppositeSide;
target.Polys[i].Links.Add(link);
//link target poly to off-mesh connection
if ((targetCon.Flags & OffMeshConnectionFlags.Bidirectional) != 0)
{
int landPolyIdx = idManager.DecodePolyIndex(ref reference);
NavPolyId id;
id = target.baseRef;
idManager.SetPolyIndex(ref id, targetCon.Poly, out id);
Link bidiLink = new Link();
bidiLink.Reference = id;
bidiLink.Edge = 0xff;
bidiLink.Side = side;
Polys[landPolyIdx].Links.Add(bidiLink);
}
}
}
/// <summary>
/// Search for neighbor polygons in the tile.
/// </summary>
/// <param name="va">Vertex A</param>
/// <param name="vb">Vertex B</param>
/// <param name="side">Polygon edge</param>
/// <param name="con">Resulting Connection polygon</param>
/// <param name="conarea">Resulting Connection area</param>
public void FindConnectingPolys(Vector3 va, Vector3 vb, BoundarySide side, List<NavPolyId> con, List<float> conarea)
{
Vector2 amin = Vector2.Zero;
Vector2 amax = Vector2.Zero;
CalcSlabEndPoints(va, vb, amin, amax, side);
float apos = GetSlabCoord(va, side);
//Remove links pointing to 'side' and compact the links array
Vector2 bmin = Vector2.Zero;
Vector2 bmax = Vector2.Zero;
//Iterate through all the tile's polygons
for (int i = 0; i < PolyCount; i++)
{
int numPolyVerts = Polys[i].VertCount;
//Iterate through all the vertices
for (int j = 0; j < numPolyVerts; j++)
{
//Skip edges which do not point to the right side
if (Polys[i].Neis[j] != (Link.External | (int)side))
continue;
//Grab two adjacent vertices
Vector3 vc = Verts[Polys[i].Verts[j]];
Vector3 vd = Verts[Polys[i].Verts[(j + 1) % numPolyVerts]];
float bpos = GetSlabCoord(vc, side);
//Segments are not close enough
if (Math.Abs(apos - bpos) > 0.01f)
continue;
//Check if the segments touch
CalcSlabEndPoints(vc, vd, bmin, bmax, side);
//Skip if slabs don't overlap
if (!OverlapSlabs(amin, amax, bmin, bmax, 0.01f, WalkableClimb))
continue;
//Add return value
if (con.Count < con.Capacity)
{
conarea.Add(Math.Max(amin.X, bmin.X));
conarea.Add(Math.Min(amax.X, bmax.X));
NavPolyId id;
idManager.SetPolyIndex(ref baseRef, i, out id);
con.Add(id);
}
break;
}
}
}
/// <summary>
/// Find the closest polygon possible in the tile under certain constraints.
/// </summary>
/// <param name="tile">Current tile</param>
/// <param name="center">Center starting point</param>
/// <param name="extents">Range of search</param>
/// <param name="nearestPt">Resulting nearest point</param>
/// <returns>Polygon Reference which contains nearest point</returns>
public NavPolyId FindNearestPoly(Vector3 center, Vector3 extents, ref Vector3 nearestPt)
{
BBox3 bounds;
bounds.Min = center - extents;
bounds.Max = center + extents;
//Get nearby polygons from proximity grid
List<NavPolyId> polys = new List<NavPolyId>(128);
int polyCount = this.QueryPolygons(bounds, polys);
//Find nearest polygon amongst the nearby polygons
NavPolyId nearest = NavPolyId.Null;
float nearestDistanceSqr = float.MaxValue;
//Iterate throuh all the polygons
for (int i = 0; i < polyCount; i++)
{
NavPolyId reference = polys[i];
Vector3 closestPtPoly = new Vector3();
ClosestPointOnPoly(idManager.DecodePolyIndex(ref reference), center, ref closestPtPoly);
float d = (center - closestPtPoly).LengthSquared();
if (d < nearestDistanceSqr)
{
nearestPt = closestPtPoly;
nearestDistanceSqr = d;
nearest = reference;
}
}
return nearest;
}
/// <summary>
/// Find all the polygons within a certain bounding box.
/// </summary>
/// <param name="tile">Current tile</param>
/// <param name="qbounds">The bounds</param>
/// <param name="polys">List of polygons</param>
/// <returns>Number of polygons found</returns>
public int QueryPolygons(BBox3 qbounds, List<NavPolyId> polys)
{
if (BVTree.Count != 0)
{
int node = 0;
int end = BvNodeCount;
Vector3 tbmin = Bounds.Min;
Vector3 tbmax = Bounds.Max;
//Clamp query box to world box
Vector3 qbmin = qbounds.Min;
Vector3 qbmax = qbounds.Max;
PolyBounds b;
float bminx = MathHelper.Clamp(qbmin.X, tbmin.X, tbmax.X) - tbmin.X;
float bminy = MathHelper.Clamp(qbmin.Y, tbmin.Y, tbmax.Y) - tbmin.Y;
float bminz = MathHelper.Clamp(qbmin.Z, tbmin.Z, tbmax.Z) - tbmin.Z;
float bmaxx = MathHelper.Clamp(qbmax.X, tbmin.X, tbmax.X) - tbmin.X;
float bmaxy = MathHelper.Clamp(qbmax.Y, tbmin.Y, tbmax.Y) - tbmin.Y;
float bmaxz = MathHelper.Clamp(qbmax.Z, tbmin.Z, tbmax.Z) - tbmin.Z;
const int MinMask = unchecked((int)0xfffffffe);
b.Min.X = (int)(bminx * BvQuantFactor) & MinMask;
b.Min.Y = (int)(bminy * BvQuantFactor) & MinMask;
b.Min.Z = (int)(bminz * BvQuantFactor) & MinMask;
b.Max.X = (int)(bmaxx * BvQuantFactor + 1) | 1;
b.Max.Y = (int)(bmaxy * BvQuantFactor + 1) | 1;
b.Max.Z = (int)(bmaxz * BvQuantFactor + 1) | 1;
//traverse tree
while (node < end)
{
BVTree.Node bvNode = BVTree[node];
bool overlap = PolyBounds.Overlapping(ref b, ref bvNode.Bounds);
bool isLeafNode = bvNode.Index >= 0;
if (isLeafNode && overlap)
{
NavPolyId polyRef;
idManager.SetPolyIndex(ref baseRef, bvNode.Index, out polyRef);
polys.Add(polyRef);
}
if (overlap || isLeafNode)
{
node++;
}
else
{
int escapeIndex = -bvNode.Index;
node += escapeIndex;
}
}
return polys.Count;
}
else
{
BBox3 b;
for (int i = 0; i < PolyCount; i++)
{
var poly = Polys[i];
//don't return off-mesh connection polygons
if (poly.PolyType == NavPolyType.OffMeshConnection)
continue;
//calculate polygon bounds
b.Max = b.Min = Verts[poly.Verts[0]];
for (int j = 1; j < poly.VertCount; j++)
{
Vector3 v = Verts[poly.Verts[j]];
Vector3Extensions.ComponentMin(ref b.Min, ref v, out b.Min);
Vector3Extensions.ComponentMax(ref b.Max, ref v, out b.Max);
}
if (BBox3.Overlapping(ref qbounds, ref b))
{
NavPolyId polyRef;
idManager.SetPolyIndex(ref baseRef, i, out polyRef);
polys.Add(polyRef);
}
}
return polys.Count;
}
}
/// <summary>
/// Find the slab endpoints based off of the 'side' value.
/// </summary>
/// <param name="va">Vertex A</param>
/// <param name="vb">Vertex B</param>
/// <param name="bmin">Minimum bounds</param>
/// <param name="bmax">Maximum bounds</param>
/// <param name="side">The side</param>
public static void CalcSlabEndPoints(Vector3 va, Vector3 vb, Vector2 bmin, Vector2 bmax, BoundarySide side)
{
if (side == BoundarySide.PlusX || side == BoundarySide.MinusX)
{
if (va.Z < vb.Z)
{
bmin.X = va.Z;
bmin.Y = va.Y;
bmax.X = vb.Z;
bmax.Y = vb.Y;
}
else
{
bmin.X = vb.Z;
bmin.Y = vb.Y;
bmax.X = va.Z;
bmax.Y = va.Y;
}
}
else if (side == BoundarySide.PlusZ || side == BoundarySide.MinusZ)
{
if (va.X < vb.X)
{
bmin.X = va.X;
bmin.Y = va.Y;
bmax.X = vb.X;
bmax.Y = vb.Y;
}
else
{
bmin.X = vb.X;
bmin.Y = vb.Y;
bmax.X = va.X;
bmax.Y = va.Y;
}
}
}
/// <summary>
/// Return the proper slab coordinate value depending on the 'side' value.
/// </summary>
/// <param name="va">Vertex A</param>
/// <param name="side">The side</param>
/// <returns>Slab coordinate value</returns>
public static float GetSlabCoord(Vector3 va, BoundarySide side)
{
if (side == BoundarySide.PlusX || side == BoundarySide.MinusX)
return va.X;
else if (side == BoundarySide.PlusZ || side == BoundarySide.MinusZ)
return va.Z;
return 0;
}
/// <summary>
/// Check if two slabs overlap.
/// </summary>
/// <param name="amin">Minimum bounds A</param>
/// <param name="amax">Maximum bounds A</param>
/// <param name="bmin">Minimum bounds B</param>
/// <param name="bmax">Maximum bounds B</param>
/// <param name="px">Point's x</param>
/// <param name="py">Point's y</param>
/// <returns>True if slabs overlap</returns>
public static bool OverlapSlabs(Vector2 amin, Vector2 amax, Vector2 bmin, Vector2 bmax, float px, float py)
{
//Check for horizontal overlap
//Segment shrunk a little so that slabs which touch at endpoints aren't connected
float minX = Math.Max(amin.X + px, bmin.X + px);
float maxX = Math.Min(amax.X - px, bmax.X - px);
if (minX > maxX)
return false;
//Check vertical overlap
float leftSlope = (amax.Y - amin.Y) / (amax.X - amin.X);
float leftConstant = amin.Y - leftSlope * amin.X;
float rightSlope = (bmax.Y - bmin.Y) / (bmax.X - bmin.X);
float rightConstant = bmin.Y - rightSlope * bmin.X;
float leftMinY = leftSlope * minX + leftConstant;
float leftMaxY = leftSlope * maxX + leftConstant;
float rightMinY = rightSlope * minX + rightConstant;
float rightMaxY = rightSlope * maxX + rightConstant;
float dmin = rightMinY - leftMinY;
float dmax = rightMaxY - leftMaxY;
//Crossing segments always overlap
if (dmin * dmax < 0)
return true;
//Check for overlap at endpoints
float threshold = (py * 2) * (py * 2);
if (dmin * dmin <= threshold || dmax * dmax <= threshold)
return true;
return false;
}
/// <summary>
/// Given a point, find the closest point on that poly.
/// </summary>
/// <param name="poly">The current polygon.</param>
/// <param name="pos">The current position</param>
/// <param name="closest">Reference to the closest point</param>
public void ClosestPointOnPoly(NavPoly poly, Vector3 pos, ref Vector3 closest)
{
int indexPoly = 0;
for (int i = 0; i < Polys.Length; i++)
{
if (Polys[i] == poly)
{
indexPoly = i;
break;
}
}
ClosestPointOnPoly(indexPoly, pos, ref closest);
}
/// <summary>
/// Given a point, find the closest point on that poly.
/// </summary>
/// <param name="indexPoly">The current poly's index</param>
/// <param name="pos">The current position</param>
/// <param name="closest">Reference to the closest point</param>
public void ClosestPointOnPoly(int indexPoly, Vector3 pos, ref Vector3 closest)
{
NavPoly poly = Polys[indexPoly];
//Off-mesh connections don't have detail polygons
if (Polys[indexPoly].PolyType == NavPolyType.OffMeshConnection)
{
ClosestPointOnPolyOffMeshConnection(poly, pos, out closest);
return;
}
ClosestPointOnPolyBoundary(poly, pos, out closest);
float h;
if (ClosestHeight(indexPoly, pos, out h))
closest.Y = h;
}
/// <summary>
/// Given a point, find the closest point on that poly.
/// </summary>
/// <param name="poly">The current polygon.</param>
/// <param name="pos">The current position</param>
/// <param name="closest">Reference to the closest point</param>
public void ClosestPointOnPolyBoundary(NavPoly poly, Vector3 pos, out Vector3 closest)
{
//Clamp point to be inside the polygon
Vector3[] verts = new Vector3[PathfindingCommon.VERTS_PER_POLYGON];
float[] edgeDistance = new float[PathfindingCommon.VERTS_PER_POLYGON];
float[] edgeT = new float[PathfindingCommon.VERTS_PER_POLYGON];
int numPolyVerts = poly.VertCount;
for (int i = 0; i < numPolyVerts; i++)
verts[i] = Verts[poly.Verts[i]];
bool inside = Distance.PointToPolygonEdgeSquared(pos, verts, numPolyVerts, edgeDistance, edgeT);
if (inside)
{
//Point is inside the polygon
closest = pos;
}
else
{
//Point is outside the polygon
//Clamp to nearest edge
float minDistance = float.MaxValue;
int minIndex = -1;
for (int i = 0; i < numPolyVerts; i++)
{
if (edgeDistance[i] < minDistance)
{
minDistance = edgeDistance[i];
minIndex = i;
}
}
Vector3 va = verts[minIndex];
Vector3 vb = verts[(minIndex + 1) % numPolyVerts];
closest = Vector3.Lerp(va, vb, edgeT[minIndex]);
}
}
/// <summary>
/// Find the distance from a point to a triangle.
/// </summary>
/// <param name="indexPoly">Current polygon's index</param>
/// <param name="pos">Current position</param>
/// <param name="h">Resulting height</param>
/// <returns>True, if a height is found. False, if otherwise.</returns>
public bool ClosestHeight(int indexPoly, Vector3 pos, out float h)
{
NavPoly poly = Polys[indexPoly];
PolyMeshDetail.MeshData pd = DetailMeshes[indexPoly];
//find height at the location
for (int j = 0; j < DetailMeshes[indexPoly].TriangleCount; j++)
{
PolyMeshDetail.TriangleData t = DetailTris[pd.TriangleIndex + j];
Vector3[] v = new Vector3[3];
for (int k = 0; k < 3; k++)
{
if (t[k] < poly.VertCount)
v[k] = Verts[poly.Verts[t[k]]];
else
v[k] = DetailVerts[pd.VertexIndex + (t[k] - poly.VertCount)];
}
if (Distance.PointToTriangle(pos, v[0], v[1], v[2], out h))
return true;
}
h = float.MaxValue;
return false;
}
/// <summary>
/// Find the closest point on an offmesh connection, which is in between the two points.
/// </summary>
/// <param name="poly">Current polygon</param>
/// <param name="pos">Current position</param>
/// <param name="closest">Resulting point that is closest.</param>
public void ClosestPointOnPolyOffMeshConnection(NavPoly poly, Vector3 pos, out Vector3 closest)
{
Vector3 v0 = Verts[poly.Verts[0]];
Vector3 v1 = Verts[poly.Verts[1]];
float d0 = (pos - v0).Length();
float d1 = (pos - v1).Length();
float u = d0 / (d0 + d1);
closest = Vector3.Lerp(v0, v1, u);
}
public static bool operator==(NavTile left, NavTile right)
{
if (object.ReferenceEquals(left, right))
return true;
if (((object)left == null) || ((object)right == null))
return false;
return left.Equals(right);
}
public static bool operator !=(NavTile left, NavTile right)
{
return !(left == right);
}
public bool Equals(NavTile other)
{
//TODO use more for equals?
return this.Location == other.Location && this.Layer == other.Layer;
}
public override bool Equals(object obj)
{
NavTile other = obj as NavTile;
if (other != null)
return this.Equals(other);
else
return false;
}
public override int GetHashCode()
{
//FNV hash
unchecked
{
int h1 = (int)2166136261;
int h2 = (int)16777619;
h1 = (h1 * h2) ^ Location.X;
h1 = (h1 * h2) ^ Location.Y;
h1 = (h1 * h2) ^ Layer;
return h1;
}
}
public override string ToString()
{
return "{ Location: " + Location.ToString() + ", Layer: " + Layer.ToString() + "}";
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.VisualStudio.Composition;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public partial class TestWorkspace
{
private const string CSharpExtension = ".cs";
private const string CSharpScriptExtension = ".csx";
private const string VisualBasicExtension = ".vb";
private const string VisualBasicScriptExtension = ".vbx";
private const string WorkspaceElementName = "Workspace";
private const string ProjectElementName = "Project";
private const string SubmissionElementName = "Submission";
private const string MetadataReferenceElementName = "MetadataReference";
private const string MetadataReferenceFromSourceElementName = "MetadataReferenceFromSource";
private const string ProjectReferenceElementName = "ProjectReference";
private const string CompilationOptionsElementName = "CompilationOptions";
private const string RootNamespaceAttributeName = "RootNamespace";
private const string OutputTypeAttributeName = "OutputType";
private const string ReportDiagnosticAttributeName = "ReportDiagnostic";
private const string ParseOptionsElementName = "ParseOptions";
private const string LanguageVersionAttributeName = "LanguageVersion";
private const string DocumentationModeAttributeName = "DocumentationMode";
private const string DocumentElementName = "Document";
private const string AnalyzerElementName = "Analyzer";
private const string AssemblyNameAttributeName = "AssemblyName";
private const string CommonReferencesAttributeName = "CommonReferences";
private const string CommonReferencesWinRTAttributeName = "CommonReferencesWinRT";
private const string CommonReferencesNet45AttributeName = "CommonReferencesNet45";
private const string CommonReferencesPortableAttributeName = "CommonReferencesPortable";
private const string CommonReferenceFacadeSystemRuntimeAttributeName = "CommonReferenceFacadeSystemRuntime";
private const string FilePathAttributeName = "FilePath";
private const string FoldersAttributeName = "Folders";
private const string KindAttributeName = "Kind";
private const string LanguageAttributeName = "Language";
private const string GlobalImportElementName = "GlobalImport";
private const string IncludeXmlDocCommentsAttributeName = "IncludeXmlDocComments";
private const string IsLinkFileAttributeName = "IsLinkFile";
private const string LinkAssemblyNameAttributeName = "LinkAssemblyName";
private const string LinkProjectNameAttributeName = "LinkProjectName";
private const string LinkFilePathAttributeName = "LinkFilePath";
private const string PreprocessorSymbolsAttributeName = "PreprocessorSymbols";
private const string AnalyzerDisplayAttributeName = "Name";
private const string AnalyzerFullPathAttributeName = "FullPath";
private const string AliasAttributeName = "Alias";
private const string ProjectNameAttribute = "Name";
private const string FeaturesAttributeName = "Features";
/// <summary>
/// Creates a single buffer in a workspace.
/// </summary>
/// <param name="content">Lines of text, the buffer contents</param>
internal static Task<TestWorkspace> CreateAsync(
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
string content)
{
return CreateAsync(language, compilationOptions, parseOptions, new[] { content });
}
/// <summary>
/// Creates a single buffer in a workspace.
/// </summary>
/// <param name="content">Lines of text, the buffer contents</param>
internal static Task<TestWorkspace> CreateAsync(
string workspaceKind,
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
string content)
{
return CreateAsync(workspaceKind, language, compilationOptions, parseOptions, new[] { content });
}
/// <param name="files">Can pass in multiple file contents: files will be named test1.cs, test2.cs, etc.</param>
internal static Task<TestWorkspace> CreateAsync(
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
params string[] files)
{
return CreateAsync(language, compilationOptions, parseOptions, files, exportProvider: null);
}
/// <param name="files">Can pass in multiple file contents: files will be named test1.cs, test2.cs, etc.</param>
internal static Task<TestWorkspace> CreateAsync(
string workspaceKind,
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
params string[] files)
{
return CreateAsync(language, compilationOptions, parseOptions, files, exportProvider: null, workspaceKind: workspaceKind);
}
internal static async Task<TestWorkspace> CreateAsync(
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
string[] files,
ExportProvider exportProvider,
string[] metadataReferences = null,
string workspaceKind = null,
string extension = null,
bool commonReferences = true)
{
var documentElements = new List<XElement>();
var index = 1;
if (extension == null)
{
extension = language == LanguageNames.CSharp
? CSharpExtension
: VisualBasicExtension;
}
foreach (var file in files)
{
documentElements.Add(CreateDocumentElement(file, "test" + index++ + extension, parseOptions));
}
metadataReferences = metadataReferences ?? SpecializedCollections.EmptyArray<string>();
foreach (var reference in metadataReferences)
{
documentElements.Add(CreateMetadataReference(reference));
}
var workspaceElement = CreateWorkspaceElement(
CreateProjectElement(compilationOptions?.ModuleName ?? "Test", language, commonReferences, parseOptions, compilationOptions, documentElements));
return await CreateAsync(workspaceElement, exportProvider: exportProvider, workspaceKind: workspaceKind);
}
internal static Task<TestWorkspace> CreateAsync(
string language,
CompilationOptions compilationOptions,
ParseOptions[] parseOptions,
string[] files,
ExportProvider exportProvider)
{
Contract.Requires(parseOptions == null || (files.Length == parseOptions.Length), "Please specify a parse option for each file.");
var documentElements = new List<XElement>();
var index = 1;
var extension = "";
for (int i = 0; i < files.Length; i++)
{
if (language == LanguageNames.CSharp)
{
extension = parseOptions[i].Kind == SourceCodeKind.Regular
? CSharpExtension
: CSharpScriptExtension;
}
else if (language == LanguageNames.VisualBasic)
{
extension = parseOptions[i].Kind == SourceCodeKind.Regular
? VisualBasicExtension
: VisualBasicScriptExtension;
}
else
{
extension = language;
}
documentElements.Add(CreateDocumentElement(files[i], "test" + index++ + extension, parseOptions == null ? null : parseOptions[i]));
}
var workspaceElement = CreateWorkspaceElement(
CreateProjectElement("Test", language, true, parseOptions.FirstOrDefault(), compilationOptions, documentElements));
return CreateAsync(workspaceElement, exportProvider: exportProvider);
}
#region C#
public static Task<TestWorkspace> CreateCSharpAsync(
string file,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null)
{
return CreateCSharpAsync(new[] { file }, parseOptions, compilationOptions, exportProvider, metadataReferences);
}
public static Task<TestWorkspace> CreateCSharpAsync(
string[] files,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null)
{
return CreateAsync(LanguageNames.CSharp, compilationOptions, parseOptions, files, exportProvider, metadataReferences);
}
public static Task<TestWorkspace> CreateCSharpAsync(
string[] files,
ParseOptions[] parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null)
{
return CreateAsync(LanguageNames.CSharp, compilationOptions, parseOptions, files, exportProvider);
}
#endregion
#region VB
public static Task<TestWorkspace> CreateVisualBasicAsync(
string file,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null)
{
return CreateVisualBasicAsync(new[] { file }, parseOptions, compilationOptions, exportProvider, metadataReferences);
}
public static Task<TestWorkspace> CreateVisualBasicAsync(
string[] files,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
string[] metadataReferences = null)
{
return CreateAsync(LanguageNames.VisualBasic, compilationOptions, parseOptions, files, exportProvider, metadataReferences);
}
/// <param name="files">Can pass in multiple file contents with individual source kind: files will be named test1.vb, test2.vbx, etc.</param>
public static Task<TestWorkspace> CreateVisualBasicAsync(
string[] files,
ParseOptions[] parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null)
{
return CreateAsync(LanguageNames.VisualBasic, compilationOptions, parseOptions, files, exportProvider);
}
#endregion
}
}
| |
#region Using directives
#define USE_TRACING
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Net;
#endregion
// <summary>contains GDataRequest our thin wrapper class for request/response
// </summary>
namespace Google.GData.Client
{
/// <summary>
/// the class holds username and password to replace networkcredentials
/// </summary>
public class GDataCredentials
{
private string passWord;
/// <summary>
/// default constructor
/// </summary>
/// <param name="username">the username to use</param>
/// <param name="password">the password to use</param>
public GDataCredentials(string username, string password)
{
Username = username;
passWord = password;
}
/// <summary>
/// default constructor
/// </summary>
/// <param name="clientToken">the client login token to use</param>
public GDataCredentials(string clientToken)
{
ClientToken = clientToken;
}
/// <summary>the username used for authentication</summary>
/// <returns> </returns>
public string Username { get; set; }
/// <summary>the type of Account used</summary>
/// <returns> </returns>
public string AccountType { get; set; } = GoogleAuthentication.AccountTypeDefault;
/// <summary>in case you need to handle catpcha responses for this account</summary>
/// <returns> </returns>
public string CaptchaToken { get; set; }
/// <summary>in case you need to handle catpcha responses for this account</summary>
/// <returns> </returns>
public string CaptchaAnswer { get; set; }
/// <summary>accessor method Password</summary>
/// <returns> </returns>
public string Password
{
set { passWord = value; }
}
/// <summary>
/// returns the stored clienttoken
/// </summary>
/// <returns></returns>
public string ClientToken { get; set; }
/// <summary>
/// returns a windows conforming NetworkCredential
/// </summary>
public ICredentials NetworkCredential
{
get { return new NetworkCredential(Username, passWord); }
}
internal string getPassword()
{
return passWord;
}
}
/// <summary>base GDataRequestFactory implementation</summary>
public class GDataRequestFactory : IGDataRequestFactory
{
/// <summary>this factory's agent</summary>
public const string GDataAgent = "SA";
/// <summary>
/// the default content type for the atom envelope
/// </summary>
public const string DefaultContentType = "application/atom+xml; charset=UTF-8";
/// <summary>Cookie setting header, returned from server</summary>
public const string SetCookieHeader = "Set-Cookie";
/// <summary>Cookie client header</summary>
public const string CookieHeader = "Cookie";
/// <summary>Slug client header</summary>
public const string SlugHeader = "Slug";
/// <summary>content override header for resumable upload</summary>
public const string ContentOverrideHeader = "X-Upload-Content-Type";
/// <summary>content length header for resumable upload</summary>
public const string ContentLengthOverrideHeader = "X-Upload-Content-Length";
/// <summary>
/// constant for the Etag header
/// </summary>
public const string EtagHeader = "Etag";
/// <summary>
/// constant for the If-Match header
/// </summary>
public const string IfMatch = "If-Match";
/// <summary>
/// constant for the if-None-match header
/// </summary>
public const string IfNoneMatch = "If-None-Match";
/// <summary>
/// constant for the ifmatch value that matches everything
/// </summary>
public const string IfMatchAll = "*";
private CookieContainer cookies;
private List<string> customHeaders;
// whether or not to keep the connection alive
private string slugHeader;
// set to default by default
/// <summary>holds the user-agent</summary>
private string userAgent;
// whether https should be used
/// <summary>default constructor</summary>
public GDataRequestFactory(string userAgent)
{
this.userAgent = Utilities.ConstructUserAgent(userAgent, GetType().Name);
KeepAlive = true;
}
/// <summary>The cookie container that is used for requests.</summary>
/// <returns> </returns>
public CookieContainer Cookies
{
get
{
if (cookies == null)
{
cookies = new CookieContainer();
}
return cookies;
}
set { cookies = value; }
}
/// <summary>sets and gets the Content Type, used for binary transfers</summary>
/// <returns> </returns>
public string ContentType { get; set; } = DefaultContentType;
/// <summary>sets and gets the slug header, used for binary transfers
/// note that the data will be converted to ASCII and URLencoded on setting it
/// </summary>
/// <returns> </returns>
public string Slug
{
get { return slugHeader; }
set { slugHeader = Utilities.EncodeSlugHeader(value); }
}
/// <summary>accessor method public string UserAgent</summary>
/// <returns> </returns>
public virtual string UserAgent
{
get { return userAgent; }
set { userAgent = value; }
}
/// <summary>accessor method to the webproxy object to use</summary>
/// <returns> </returns>
public IWebProxy Proxy { get; set; }
/// <summary>indicates if the connection should be kept alive, default
/// is true</summary>
/// <returns> </returns>
public bool KeepAlive { get; set; }
/// <summary>gets and sets the Timeout property used for the created
/// HTTPRequestObject in milliseconds. if you set it to -1 it will stick
/// with the default of the HTTPRequestObject. From MSDN:
/// The number of milliseconds to wait before the request times out.
/// The default is 100,000 milliseconds (100 seconds).</summary>
/// <returns> </returns>
public int Timeout { get; set; } = -1;
internal bool hasCustomHeaders
{
get { return customHeaders != null; }
}
/// <summary>accessor method public StringArray CustomHeaders</summary>
/// <returns> </returns>
public List<string> CustomHeaders
{
get
{
if (customHeaders == null)
{
customHeaders = new List<string>();
}
return customHeaders;
}
}
/// <summary>default constructor</summary>
public virtual IGDataRequest CreateRequest(GDataRequestType type, Uri uriTarget)
{
return new GDataRequest(type, uriTarget, this);
}
/// <summary>whether or not new requests should use GZip</summary>
public bool UseGZip { get; set; }
/// <summary>indicates if the connection should use https</summary>
/// <returns> </returns>
public bool UseSSL { get; set; } = true;
}
/// <summary>base GDataRequest implementation</summary>
public class GDataRequest : IGDataRequest, IDisposable, ISupportsEtag
{
// holds the returned contentlength
// used to refresh request for batching
/// <summary>holds the contenttype to use if overridden</summary>
private string contentType;
/// <summary>holds if we are disposed</summary>
protected bool disposed;
private readonly GDataRequestFactory factory; // holds the factory to use
/// <summary>holds the timestamp for conditional GET</summary>
private DateTime ifModifiedSince = DateTime.MinValue;
/// <summary>holds the request if a stream is open</summary>
private Stream requestStream;
/// <summary>stream from the response</summary>
private Stream responseStream;
/// <summary>holds the slugheader to use if overridden</summary>
private string slugHeader;
/// <summary>holds the target Uri</summary>
private Uri targetUri;
/// <summary>holds request type</summary>
private readonly GDataRequestType type;
/// <summary>set whether or not this request should use GZip</summary>
private bool useGZip;
/// <summary>default constructor</summary>
internal GDataRequest(GDataRequestType type, Uri uriTarget, GDataRequestFactory factory)
{
this.type = type;
targetUri = uriTarget;
this.factory = factory;
useGZip = this.factory.UseGZip; // use gzip setting from factory
}
/// <summary>
/// exposing the private targetUri so that subclasses can override
/// the value for redirect handling
/// </summary>
protected Uri TargetUri
{
get { return targetUri; }
set { targetUri = value; }
}
/// <summary>sets and gets the content Type, used for binary transfers</summary>
/// <returns> </returns>
public string ContentType
{
get { return contentType == null ? factory.ContentType : contentType; }
set { contentType = value; }
}
/// <summary>sets and gets the slugHeader, used for binary transfers
/// will encode to ascii and urlencode the string on setting it.
/// </summary>
/// <returns> </returns>
public string Slug
{
get { return slugHeader == null ? factory.Slug : slugHeader; }
set { slugHeader = Utilities.EncodeSlugHeader(value); }
}
/// <summary>
/// returnes the content-length of the response, -1 if none was given
/// </summary>
/// <returns></returns>
public long ContentLength { get; private set; }
/// <summary>accessor method protected WebRequest Request</summary>
/// <returns> </returns>
protected WebRequest Request { get; set; }
/// <summary>
/// accessor method protected WebResponse Response
/// </summary>
/// <returns> </returns>
protected WebResponse Response { get; set; }
/// <summary>implements the disposable interface</summary>
public void Dispose()
{
if (responseStream != null)
{
responseStream.Close();
}
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>set whether or not this request should use GZip</summary>
public bool UseGZip
{
get { return (useGZip); }
set { useGZip = value; }
}
/// <summary>set a timestamp for conditional GET</summary>
public DateTime IfModifiedSince
{
get { return (ifModifiedSince); }
set { ifModifiedSince = value; }
}
/// <summary>
/// accessor method for the GDataCredentials used
/// </summary>
/// <returns> </returns>
public GDataCredentials Credentials { get; set; }
/// <summary>copy of batch request content</summary>
public AtomBase ContentStore { get; set; }
/// <summary>denotes if it's a batch request</summary>
public bool IsBatch { get; set; }
/// <summary>returns the writable request stream</summary>
/// <returns> the stream to write into</returns>
public virtual Stream GetRequestStream()
{
EnsureWebRequest();
requestStream = Request.GetRequestStream();
return requestStream;
}
/// <summary>Executes the request and prepares the response stream. Also
/// does error checking</summary>
public virtual void Execute()
{
try
{
EnsureWebRequest();
// if we ever handed out a stream, we want to close it before doing the real excecution
if (requestStream != null)
{
requestStream.Close();
}
Tracing.TraceCall("calling the real execution over the webresponse");
LogRequest(Request);
Response = Request.GetResponse();
}
catch (WebException e)
{
Tracing.TraceCall("GDataRequest::Execute failed: " + targetUri);
GDataRequestException gde = new GDataRequestException("Execution of request failed: " + targetUri, e);
throw gde;
}
if (Response != null)
{
responseStream = Response.GetResponseStream();
}
LogResponse(Response);
if (Response is HttpWebResponse)
{
HttpWebResponse response = Response as HttpWebResponse;
HttpWebRequest request = Request as HttpWebRequest;
useGZip = (string.Compare(response.ContentEncoding, "gzip", true, CultureInfo.InvariantCulture) == 0);
if (useGZip)
{
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
}
Tracing.Assert(response != null, "The response should not be NULL");
Tracing.Assert(request != null, "The request should not be NULL");
int code = (int) response.StatusCode;
Tracing.TraceMsg("Returned ContentType is: " +
(response.ContentType == null ? "None" : response.ContentType) + " from URI : " +
request.RequestUri);
;
Tracing.TraceMsg("Returned StatusCode is: " + response.StatusCode + code);
if (response.StatusCode == HttpStatusCode.Forbidden)
{
// that could imply that we need to reauthenticate
Tracing.TraceMsg("need to reauthenticate");
throw new GDataForbiddenException("Execution of request returned HttpStatusCode.Forbidden: " +
targetUri + response.StatusCode, Response);
}
if (response.StatusCode == HttpStatusCode.Conflict)
{
// a put went bad due to a version conflict
throw new GDataVersionConflictException("Execution of request returned HttpStatusCode.Conflict: " +
targetUri + response.StatusCode, Response);
}
if ((IfModifiedSince != DateTime.MinValue || Etag != null)
&& response.StatusCode == HttpStatusCode.NotModified)
{
// Throw an exception for conditional GET
throw new GDataNotModifiedException("Content not modified: " + targetUri, Response);
}
if (response.StatusCode == HttpStatusCode.Redirect ||
response.StatusCode == HttpStatusCode.Found ||
response.StatusCode == HttpStatusCode.RedirectKeepVerb)
{
Tracing.TraceMsg("throwing for redirect");
throw new GDataRedirectException("Execution resulted in a redirect from " + targetUri, Response);
}
if (code > 299)
{
// treat everything else over 300 as errors
throw new GDataRequestException("Execution of request returned unexpected result: " + targetUri +
response.StatusCode, Response);
}
ContentLength = response.ContentLength;
// if we got an etag back, remember it
Etag = response.Headers[GDataRequestFactory.EtagHeader];
response = null;
request = null;
}
}
/// <summary>gets the readable response stream</summary>
/// <returns> the response stream</returns>
public virtual Stream GetResponseStream()
{
return (responseStream);
}
/// <summary>sets and gets the etag header value, used for concurrency</summary>
/// <returns> </returns>
public string Etag { get; set; }
/// <summary>does the real disposition</summary>
/// <param name="disposing">indicates if dispose called it or finalize</param>
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
Tracing.TraceMsg("disposing of request");
Reset();
disposed = true;
}
}
/// <summary>resets the object's state</summary>
protected virtual void Reset()
{
requestStream = null;
Request = null;
if (Response != null)
{
Response.Close();
}
Response = null;
}
/// <summary>ensures that the correct HTTP verb is set on the stream</summary>
protected virtual void EnsureWebRequest()
{
if (Request == null && targetUri != null)
{
if (factory.UseSSL && !targetUri.Scheme.ToLower().Equals("https"))
{
targetUri = new Uri("https://" + targetUri.Host + targetUri.PathAndQuery);
}
Request = WebRequest.Create(targetUri);
Response = null;
if (Request == null)
{
throw new OutOfMemoryException("Could not create a new Webrequest");
}
HttpWebRequest web = Request as HttpWebRequest;
if (web != null)
{
switch (type)
{
case GDataRequestType.Delete:
web.Method = HttpMethods.Delete;
break;
case GDataRequestType.Update:
web.Method = HttpMethods.Put;
break;
case GDataRequestType.Batch:
case GDataRequestType.Insert:
web.Method = HttpMethods.Post;
break;
case GDataRequestType.Query:
web.Method = HttpMethods.Get;
break;
}
if (useGZip)
{
web.Headers.Set("Accept-Encoding", "gzip");
}
if (Etag != null)
{
if (Etag != GDataRequestFactory.IfMatchAll)
{
web.Headers.Set(GDataRequestFactory.EtagHeader, Etag);
}
switch (type)
{
case GDataRequestType.Update:
case GDataRequestType.Delete:
if (!Utilities.IsWeakETag(this))
{
web.Headers.Set(GDataRequestFactory.IfMatch, Etag);
}
break;
case GDataRequestType.Query:
web.Headers.Set(GDataRequestFactory.IfNoneMatch, Etag);
break;
}
}
if (IfModifiedSince != DateTime.MinValue)
{
web.IfModifiedSince = IfModifiedSince;
}
web.ContentType = ContentType;
web.UserAgent = factory.UserAgent;
web.KeepAlive = factory.KeepAlive;
web.CookieContainer = factory.Cookies;
// add all custom headers
if (factory.hasCustomHeaders)
{
foreach (string s in factory.CustomHeaders)
{
Request.Headers.Add(s);
}
}
if (factory.Timeout != -1)
{
web.Timeout = factory.Timeout;
}
if (Slug != null)
{
Request.Headers.Set(GDataRequestFactory.SlugHeader, Slug);
}
if (factory.Proxy != null)
{
Request.Proxy = factory.Proxy;
}
}
EnsureCredentials();
}
}
/// <summary>sets up the correct credentials for this call, pending
/// security scheme</summary>
protected virtual void EnsureCredentials()
{
if (Credentials != null)
{
Request.Credentials = Credentials.NetworkCredential;
}
}
/// <summary>Logs the request object if overridden in subclass</summary>
/// <param name="request">the request to log</param>
protected virtual void LogRequest(WebRequest request)
{
}
/// <summary>Logs the response object if overridden in subclass</summary>
/// <param name="response">the response to log</param>
protected virtual void LogResponse(WebResponse response)
{
}
/// <summary>returns a valid web request with the correct credentials</summary>
/// <returns>the HTTP web request</returns>
public HttpWebRequest GetFinalizedRequest()
{
EnsureWebRequest();
EnsureCredentials();
return Request as HttpWebRequest;
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using ServiceStack.Logging;
using ServiceStack.Service;
using ServiceStack.Text;
namespace ServiceStack.ServiceClient.Web
{
/**
* Need to provide async request options
* http://msdn.microsoft.com/en-us/library/86wf6409(VS.71).aspx
*/
public abstract class AsyncServiceClientBase : IAsyncServiceClient
{
private static readonly ILog Log = LogManager.GetLogger(typeof(AsyncServiceClientBase));
public static Action<HttpWebRequest> HttpWebRequestFilter { get; set; }
public const string DefaultHttpMethod = "POST";
const int BufferSize = 1024;
internal class RequestState<TResponse>
{
public RequestState()
{
BufferRead = new byte[BufferSize];
RequestData = new StringBuilder();
Request = null;
ResponseStream = null;
}
public string Url;
public StringBuilder RequestData;
public byte[] BufferRead;
public HttpWebRequest Request;
public HttpWebResponse Response;
public Stream ResponseStream;
public int Completed;
public Timer Timer;
public Action<TResponse> OnSuccess;
public Action<TResponse, Exception> OnError;
public void StartTimer(TimeSpan timeOut)
{
this.Timer = new Timer(this.TimedOut, this, (int)timeOut.TotalMilliseconds, System.Threading.Timeout.Infinite);
}
public void TimedOut(object state)
{
if (Interlocked.Increment(ref Completed) == 1)
{
if (this.Request != null)
{
this.Request.Abort();
}
}
this.Timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
this.Timer.Dispose();
}
}
protected AsyncServiceClientBase()
{
this.HttpMethod = DefaultHttpMethod;
this.Timeout = TimeSpan.FromSeconds(60);
}
protected AsyncServiceClientBase(string syncReplyBaseUri, string asyncOneWayBaseUri)
: this()
{
this.SyncReplyBaseUri = syncReplyBaseUri;
this.AsyncOneWayBaseUri = asyncOneWayBaseUri;
}
public string BaseUri
{
set
{
var baseUri = value.WithTrailingSlash();
this.SyncReplyBaseUri = baseUri + "SyncReply/";
this.AsyncOneWayBaseUri = baseUri + "AsyncOneWay/";
}
}
public string SyncReplyBaseUri { get; set; }
public string AsyncOneWayBaseUri { get; set; }
public TimeSpan Timeout { get; set; }
public abstract string ContentType { get; }
public string HttpMethod { get; set; }
public abstract void SerializeToStream(object request, Stream stream);
public abstract T DeserializeFromStream<T>(Stream stream);
public void SendAsync<TResponse>(object request, Action<TResponse> onSuccess)
{
SendAsync(request, onSuccess, null);
}
public void SendAsync<TResponse>(object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
var requestUri = this.SyncReplyBaseUri.WithTrailingSlash() + request.GetType().Name;
var isHttpGet = HttpMethod != null && HttpMethod.ToUpper() == "GET";
if (isHttpGet)
{
var queryString = QueryStringSerializer.SerializeToString(request);
if (!string.IsNullOrEmpty(queryString))
{
requestUri += "?" + queryString;
}
}
var webRequest = (HttpWebRequest)WebRequest.Create(requestUri);
var requestState = new RequestState<TResponse>
{
Url = requestUri,
Request = webRequest,
OnSuccess = onSuccess,
OnError = onError,
};
requestState.StartTimer(this.Timeout);
webRequest.Accept = string.Format("{0}, */*", ContentType);
webRequest.Method = HttpMethod ?? DefaultHttpMethod;
if (HttpWebRequestFilter != null)
{
HttpWebRequestFilter(webRequest);
}
if (!isHttpGet)
{
webRequest.ContentType = ContentType;
//TODO: change to use: webRequest.BeginGetRequestStream()
using (var requestStream = webRequest.GetRequestStream())
{
SerializeToStream(request, requestStream);
}
}
var result = webRequest.BeginGetResponse(ResponseCallback<TResponse>, requestState);
}
private void ResponseCallback<T>(IAsyncResult asyncResult)
{
var requestState = (RequestState<T>)asyncResult.AsyncState;
try
{
var webRequest = requestState.Request;
requestState.Response = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
// Read the response into a Stream object.
var responseStream = requestState.Response.GetResponseStream();
requestState.ResponseStream = responseStream;
var asyncRead = responseStream.BeginRead(requestState.BufferRead, 0, BufferSize, ReadCallBack<T>, requestState);
return;
}
catch (Exception e)
{
HandleResponseError(e, requestState);
}
//allDone.Set();
}
private void ReadCallBack<T>(IAsyncResult asyncResult)
{
var requestState = (RequestState<T>)asyncResult.AsyncState;
try
{
var responseStream = requestState.ResponseStream;
int read = responseStream.EndRead(asyncResult);
if (read > 0)
{
requestState.RequestData.Append(Encoding.UTF8.GetString(requestState.BufferRead, 0, read));
var nextAsyncResult = responseStream.BeginRead(
requestState.BufferRead, 0, BufferSize, ReadCallBack<T>, requestState);
return;
}
Interlocked.Increment(ref requestState.Completed);
var response = default(T);
try
{
response = DeserializeFromStream<T>(responseStream);
}
catch (Exception ex)
{
Log.Debug(string.Format("Error Reading Response Error: {0}", ex.Message), ex);
if (requestState.OnError != null) requestState.OnError(default(T), ex);
}
finally
{
responseStream.Close();
}
if (requestState.OnSuccess != null)
{
requestState.OnSuccess(response);
}
}
catch (Exception ex)
{
HandleResponseError(ex, requestState);
}
//allDone.Set();
}
public void SendOneWay<TResponse>(object request, Action<TResponse, Exception> error)
{
throw new NotImplementedException();
}
private void HandleResponseError<TResponse>(Exception exception, RequestState<TResponse> requestState)
{
var webEx = exception as WebException;
if (webEx != null && webEx.Status == WebExceptionStatus.ProtocolError)
{
var errorResponse = ((HttpWebResponse)webEx.Response);
Log.Error(webEx);
Log.DebugFormat("Status Code : {0}", errorResponse.StatusCode);
Log.DebugFormat("Status Description : {0}", errorResponse.StatusDescription);
if (requestState.OnError == null) return;
try
{
using (var stream = errorResponse.GetResponseStream())
{
var response = DeserializeFromStream<TResponse>(stream);
requestState.OnError(response, new Exception("Web Service Exception"));
}
}
catch (WebException ex)
{
// Oh, well, we tried
Log.Debug(string.Format("WebException Reading Response Error: {0}", ex.Message), ex);
requestState.OnError(default(TResponse), ex);
}
return;
}
var authEx = exception as AuthenticationException;
if (authEx != null)
{
var customEx = WebRequestUtils.CreateCustomException(requestState.Url, authEx);
Log.Debug(string.Format("AuthenticationException: {0}", customEx.Message), customEx);
if (requestState.OnError != null) requestState.OnError(default(TResponse), authEx);
}
Log.Debug(string.Format("Exception Reading Response Error: {0}", exception.Message), exception);
if (requestState.OnError != null) requestState.OnError(default(TResponse), exception);
}
public void SendOneWay(object request)
{
throw new NotImplementedException();
}
public void Dispose() { }
}
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE 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;
namespace Spine {
public class Skeleton {
internal SkeletonData data;
internal ExposedList<Bone> bones;
internal ExposedList<Slot> slots;
internal ExposedList<Slot> drawOrder;
internal ExposedList<IkConstraint> ikConstraints, ikConstraintsSorted;
internal ExposedList<TransformConstraint> transformConstraints;
internal ExposedList<PathConstraint> pathConstraints;
internal ExposedList<IUpdatable> updateCache = new ExposedList<IUpdatable>();
internal Skin skin;
internal float r = 1, g = 1, b = 1, a = 1;
internal float time;
internal bool flipX, flipY;
internal float x, y;
public SkeletonData Data { get { return data; } }
public ExposedList<Bone> Bones { get { return bones; } }
public ExposedList<IUpdatable> UpdateCacheList { get { return updateCache; } }
public ExposedList<Slot> Slots { get { return slots; } }
public ExposedList<Slot> DrawOrder { get { return drawOrder; } }
public ExposedList<IkConstraint> IkConstraints { get { return ikConstraints; } }
public ExposedList<PathConstraint> PathConstraints { get { return pathConstraints; } }
public ExposedList<TransformConstraint> TransformConstraints { get { return transformConstraints; } }
public Skin Skin { get { return skin; } set { skin = value; } }
public float R { get { return r; } set { r = value; } }
public float G { get { return g; } set { g = value; } }
public float B { get { return b; } set { b = value; } }
public float A { get { return a; } set { a = value; } }
public float Time { get { return time; } set { time = value; } }
public float X { get { return x; } set { x = value; } }
public float Y { get { return y; } set { y = value; } }
public bool FlipX { get { return flipX; } set { flipX = value; } }
public bool FlipY { get { return flipY; } set { flipY = value; } }
public Bone RootBone {
get { return bones.Count == 0 ? null : bones.Items[0]; }
}
public Skeleton (SkeletonData data) {
if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
this.data = data;
bones = new ExposedList<Bone>(data.bones.Count);
foreach (BoneData boneData in data.bones) {
Bone bone;
if (boneData.parent == null) {
bone = new Bone(boneData, this, null);
} else {
Bone parent = bones.Items[boneData.parent.index];
bone = new Bone(boneData, this, parent);
parent.children.Add(bone);
}
bones.Add(bone);
}
slots = new ExposedList<Slot>(data.slots.Count);
drawOrder = new ExposedList<Slot>(data.slots.Count);
foreach (SlotData slotData in data.slots) {
Bone bone = bones.Items[slotData.boneData.index];
Slot slot = new Slot(slotData, bone);
slots.Add(slot);
drawOrder.Add(slot);
}
ikConstraints = new ExposedList<IkConstraint>(data.ikConstraints.Count);
ikConstraintsSorted = new ExposedList<IkConstraint>(data.ikConstraints.Count);
foreach (IkConstraintData ikConstraintData in data.ikConstraints)
ikConstraints.Add(new IkConstraint(ikConstraintData, this));
transformConstraints = new ExposedList<TransformConstraint>(data.transformConstraints.Count);
foreach (TransformConstraintData transformConstraintData in data.transformConstraints)
transformConstraints.Add(new TransformConstraint(transformConstraintData, this));
pathConstraints = new ExposedList<PathConstraint> (data.pathConstraints.Count);
foreach (PathConstraintData pathConstraintData in data.pathConstraints)
pathConstraints.Add(new PathConstraint(pathConstraintData, this));
UpdateCache();
UpdateWorldTransform();
}
/// <summary>Caches information about bones and constraints. Must be called if bones, constraints or weighted path attachments are added
/// or removed.</summary>
public void UpdateCache () {
ExposedList<IUpdatable> updateCache = this.updateCache;
updateCache.Clear();
ExposedList<Bone> bones = this.bones;
for (int i = 0, n = bones.Count; i < n; i++)
bones.Items[i].sorted = false;
ExposedList<IkConstraint> ikConstraints = this.ikConstraintsSorted;
ikConstraints.Clear();
ikConstraints.AddRange(this.ikConstraints);
int ikCount = ikConstraints.Count;
for (int i = 0, level, n = ikCount; i < n; i++) {
IkConstraint ik = ikConstraints.Items[i];
Bone bone = ik.bones.Items[0].parent;
for (level = 0; bone != null; level++)
bone = bone.parent;
ik.level = level;
}
for (int i = 1, ii; i < ikCount; i++) {
IkConstraint ik = ikConstraints.Items[i];
int level = ik.level;
for (ii = i - 1; ii >= 0; ii--) {
IkConstraint other = ikConstraints.Items[ii];
if (other.level < level) break;
ikConstraints.Items[ii + 1] = other;
}
ikConstraints.Items[ii + 1] = ik;
}
for (int i = 0, n = ikConstraints.Count; i < n; i++) {
IkConstraint constraint = ikConstraints.Items[i];
Bone target = constraint.target;
SortBone(target);
ExposedList<Bone> constrained = constraint.bones;
Bone parent = constrained.Items[0];
SortBone(parent);
updateCache.Add(constraint);
SortReset(parent.children);
constrained.Items[constrained.Count - 1].sorted = true;
}
ExposedList<PathConstraint> pathConstraints = this.pathConstraints;
for (int i = 0, n = pathConstraints.Count; i < n; i++) {
PathConstraint constraint = pathConstraints.Items[i];
Slot slot = constraint.target;
int slotIndex = slot.data.index;
Bone slotBone = slot.bone;
if (skin != null) SortPathConstraintAttachment(skin, slotIndex, slotBone);
if (data.defaultSkin != null && data.defaultSkin != skin)
SortPathConstraintAttachment(data.defaultSkin, slotIndex, slotBone);
for (int ii = 0, nn = data.skins.Count; ii < nn; ii++)
SortPathConstraintAttachment(data.skins.Items[ii], slotIndex, slotBone);
PathAttachment attachment = slot.Attachment as PathAttachment;
if (attachment != null) SortPathConstraintAttachment(attachment, slotBone);
ExposedList<Bone> constrained = constraint.bones;
int boneCount = constrained.Count;
for (int ii = 0; ii < boneCount; ii++)
SortBone(constrained.Items[ii]);
updateCache.Add(constraint);
for (int ii = 0; ii < boneCount; ii++)
SortReset(constrained.Items[ii].children);
for (int ii = 0; ii < boneCount; ii++)
constrained.Items[ii].sorted = true;
}
ExposedList<TransformConstraint> transformConstraints = this.transformConstraints;
for (int i = 0, n = transformConstraints.Count; i < n; i++) {
TransformConstraint constraint = transformConstraints.Items[i];
SortBone(constraint.target);
ExposedList<Bone> constrained = constraint.bones;
int boneCount = constrained.Count;
for (int ii = 0; ii < boneCount; ii++)
SortBone(constrained.Items[ii]);
updateCache.Add(constraint);
for (int ii = 0; ii < boneCount; ii++)
SortReset(constrained.Items[ii].children);
for (int ii = 0; ii < boneCount; ii++)
constrained.Items[ii].sorted = true;
}
for (int i = 0, n = bones.Count; i < n; i++)
SortBone(bones.Items[i]);
}
private void SortPathConstraintAttachment (Skin skin, int slotIndex, Bone slotBone) {
foreach (var entry in skin.Attachments)
if (entry.Key.slotIndex == slotIndex) SortPathConstraintAttachment(entry.Value, slotBone);
}
private void SortPathConstraintAttachment (Attachment attachment, Bone slotBone) {
var pathAttachment = attachment as PathAttachment;
if (pathAttachment == null) return;
int[] pathBones = pathAttachment.bones;
if (pathBones == null)
SortBone(slotBone);
else {
var bones = this.bones;
for (int i = 0, n = pathBones.Length; i < n; i++)
SortBone(bones.Items[pathBones[i]]);
}
}
private void SortBone (Bone bone) {
if (bone.sorted) return;
Bone parent = bone.parent;
if (parent != null) SortBone(parent);
bone.sorted = true;
updateCache.Add(bone);
}
private void SortReset (ExposedList<Bone> bones) {
var bonesItems = bones.Items;
for (int i = 0, n = bones.Count; i < n; i++) {
Bone bone = bonesItems[i];
if (bone.sorted) SortReset(bone.children);
bone.sorted = false;
}
}
/// <summary>Updates the world transform for each bone and applies constraints.</summary>
public void UpdateWorldTransform () {
var updateItems = this.updateCache.Items;
for (int i = 0, n = updateCache.Count; i < n; i++)
updateItems[i].Update();
}
/// <summary>Sets the bones, constraints, and slots to their setup pose values.</summary>
public void SetToSetupPose () {
SetBonesToSetupPose();
SetSlotsToSetupPose();
}
/// <summary>Sets the bones and constraints to their setup pose values.</summary>
public void SetBonesToSetupPose () {
var bonesItems = this.bones.Items;
for (int i = 0, n = bones.Count; i < n; i++)
bonesItems[i].SetToSetupPose();
var ikConstraintsItems = this.ikConstraints.Items;
for (int i = 0, n = ikConstraints.Count; i < n; i++) {
IkConstraint constraint = ikConstraintsItems[i];
constraint.bendDirection = constraint.data.bendDirection;
constraint.mix = constraint.data.mix;
}
var transformConstraintsItems = this.transformConstraints.Items;
for (int i = 0, n = transformConstraints.Count; i < n; i++) {
TransformConstraint constraint = transformConstraintsItems[i];
TransformConstraintData data = constraint.data;
constraint.rotateMix = data.rotateMix;
constraint.translateMix = data.translateMix;
constraint.scaleMix = data.scaleMix;
constraint.shearMix = data.shearMix;
}
var pathConstraintItems = this.pathConstraints.Items;
for (int i = 0, n = pathConstraints.Count; i < n; i++) {
PathConstraint constraint = pathConstraintItems[i];
PathConstraintData data = constraint.data;
constraint.position = data.position;
constraint.spacing = data.spacing;
constraint.rotateMix = data.rotateMix;
constraint.translateMix = data.translateMix;
}
}
public void SetSlotsToSetupPose () {
var slots = this.slots;
var slotsItems = slots.Items;
drawOrder.Clear();
for (int i = 0, n = slots.Count; i < n; i++)
drawOrder.Add(slotsItems[i]);
for (int i = 0, n = slots.Count; i < n; i++)
slotsItems[i].SetToSetupPose();
}
/// <returns>May be null.</returns>
public Bone FindBone (String boneName) {
if (boneName == null) throw new ArgumentNullException("boneName", "boneName cannot be null.");
var bones = this.bones;
var bonesItems = bones.Items;
for (int i = 0, n = bones.Count; i < n; i++) {
Bone bone = bonesItems[i];
if (bone.data.name == boneName) return bone;
}
return null;
}
/// <returns>-1 if the bone was not found.</returns>
public int FindBoneIndex (String boneName) {
if (boneName == null) throw new ArgumentNullException("boneName", "boneName cannot be null.");
var bones = this.bones;
var bonesItems = bones.Items;
for (int i = 0, n = bones.Count; i < n; i++)
if (bonesItems[i].data.name == boneName) return i;
return -1;
}
/// <returns>May be null.</returns>
public Slot FindSlot (String slotName) {
if (slotName == null) throw new ArgumentNullException("slotName", "slotName cannot be null.");
var slots = this.slots;
var slotsItems = slots.Items;
for (int i = 0, n = slots.Count; i < n; i++) {
Slot slot = slotsItems[i];
if (slot.data.name == slotName) return slot;
}
return null;
}
/// <returns>-1 if the bone was not found.</returns>
public int FindSlotIndex (String slotName) {
if (slotName == null) throw new ArgumentNullException("slotName", "slotName cannot be null.");
var slots = this.slots;
var slotsItems = slots.Items;
for (int i = 0, n = slots.Count; i < n; i++)
if (slotsItems[i].data.name.Equals(slotName)) return i;
return -1;
}
/// <summary>Sets a skin by name (see SetSkin).</summary>
public void SetSkin (String skinName) {
Skin skin = data.FindSkin(skinName);
if (skin == null) throw new ArgumentException("Skin not found: " + skinName, "skinName");
SetSkin(skin);
}
/// <summary>Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default
/// skin}. Attachmentsfrom the new skin are attached if the corresponding attachment from the old skin was attached. If
/// there was no old skin, each slot's setup mode attachment is attached from the new skin.</summary>
/// <param name="newSkin">May be null.</param>
public void SetSkin (Skin newSkin) {
if (newSkin != null) {
if (skin != null)
newSkin.AttachAll(this, skin);
else {
ExposedList<Slot> slots = this.slots;
for (int i = 0, n = slots.Count; i < n; i++) {
Slot slot = slots.Items[i];
String name = slot.data.attachmentName;
if (name != null) {
Attachment attachment = newSkin.GetAttachment(i, name);
if (attachment != null) slot.Attachment = attachment;
}
}
}
}
skin = newSkin;
}
/// <returns>May be null.</returns>
public Attachment GetAttachment (String slotName, String attachmentName) {
return GetAttachment(data.FindSlotIndex(slotName), attachmentName);
}
/// <returns>May be null.</returns>
public Attachment GetAttachment (int slotIndex, String attachmentName) {
if (attachmentName == null) throw new ArgumentNullException("attachmentName", "attachmentName cannot be null.");
if (skin != null) {
Attachment attachment = skin.GetAttachment(slotIndex, attachmentName);
if (attachment != null) return attachment;
}
if (data.defaultSkin != null) return data.defaultSkin.GetAttachment(slotIndex, attachmentName);
return null;
}
/// <param name="attachmentName">May be null.</param>
public void SetAttachment (String slotName, String attachmentName) {
if (slotName == null) throw new ArgumentNullException("slotName", "slotName cannot be null.");
ExposedList<Slot> slots = this.slots;
for (int i = 0, n = slots.Count; i < n; i++) {
Slot slot = slots.Items[i];
if (slot.data.name == slotName) {
Attachment attachment = null;
if (attachmentName != null) {
attachment = GetAttachment(i, attachmentName);
if (attachment == null) throw new Exception("Attachment not found: " + attachmentName + ", for slot: " + slotName);
}
slot.Attachment = attachment;
return;
}
}
throw new Exception("Slot not found: " + slotName);
}
/// <returns>May be null.</returns>
public IkConstraint FindIkConstraint (String constraintName) {
if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null.");
ExposedList<IkConstraint> ikConstraints = this.ikConstraints;
for (int i = 0, n = ikConstraints.Count; i < n; i++) {
IkConstraint ikConstraint = ikConstraints.Items[i];
if (ikConstraint.data.name == constraintName) return ikConstraint;
}
return null;
}
/// <returns>May be null.</returns>
public TransformConstraint FindTransformConstraint (String constraintName) {
if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null.");
ExposedList<TransformConstraint> transformConstraints = this.transformConstraints;
for (int i = 0, n = transformConstraints.Count; i < n; i++) {
TransformConstraint transformConstraint = transformConstraints.Items[i];
if (transformConstraint.data.name == constraintName) return transformConstraint;
}
return null;
}
/// <returns>May be null.</returns>
public PathConstraint FindPathConstraint (String constraintName) {
if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null.");
ExposedList<PathConstraint> pathConstraints = this.pathConstraints;
for (int i = 0, n = pathConstraints.Count; i < n; i++) {
PathConstraint constraint = pathConstraints.Items[i];
if (constraint.data.name.Equals(constraintName)) return constraint;
}
return null;
}
public void Update (float delta) {
time += delta;
}
}
}
| |
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 WebApiEfDemo.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 UnityEngine;
using System;
using System.Collections;
namespace UMA
{
/// <summary>
/// Overlay color data.
/// </summary>
[System.Serializable]
public class OverlayColorData : System.IEquatable<OverlayColorData>
{
public const string UNSHARED = "-";
public string name;
public Color[] channelMask;
public Color[] channelAdditiveMask;
public Color color { get { return channelMask[0]; } set { channelMask[0] = value; } }
/// <summary>
/// Default constructor
/// </summary>
public OverlayColorData()
{
}
/// <summary>
/// Constructor for a given number of channels.
/// </summary>
/// <param name="channels">Channels.</param>
public OverlayColorData(int channels)
{
channelMask = new Color[channels];
channelAdditiveMask = new Color[channels];
for(int i= 0; i < channels; i++ )
{
channelMask[i] = Color.white;
channelAdditiveMask[i] = new Color(0,0,0,0);
}
}
/// <summary>
/// Deep copy of the OverlayColorData.
/// </summary>
public OverlayColorData Duplicate()
{
var res = new OverlayColorData();
res.name = name;
res.channelMask = new Color[channelMask.Length];
for (int i = 0; i < channelMask.Length; i++)
{
res.channelMask[i] = channelMask[i];
}
res.channelAdditiveMask = new Color[channelAdditiveMask.Length];
for (int i = 0; i < channelAdditiveMask.Length; i++)
{
res.channelAdditiveMask[i] = channelAdditiveMask[i];
}
return res;
}
/// <summary>
/// Does the OverlayColorData have a valid name?
/// </summary>
/// <returns><c>true</c> if this instance has a valid name; otherwise, <c>false</c>.</returns>
public bool HasName()
{
return ((name != null) && (name.Length > 0));
}
/// <summary>
/// Are two Unity Colors the same?
/// </summary>
/// <returns><c>true</c>, if colors are identical, <c>false</c> otherwise.</returns>
/// <param name="color1">Color1.</param>
/// <param name="color2">Color2.</param>
public static bool SameColor(Color color1, Color color2)
{
return (Mathf.Approximately(color1.r, color2.r) &&
Mathf.Approximately(color1.g, color2.g) &&
Mathf.Approximately(color1.b, color2.b) &&
Mathf.Approximately(color1.a, color2.a));
}
/// <summary>
/// Are two Unity Colors different?
/// </summary>
/// <returns><c>true</c>, if colors are different, <c>false</c> otherwise.</returns>
/// <param name="color1">Color1.</param>
/// <param name="color2">Color2.</param>
public static bool DifferentColor(Color color1, Color color2)
{
return (!Mathf.Approximately(color1.r, color2.r) ||
!Mathf.Approximately(color1.g, color2.g) ||
!Mathf.Approximately(color1.b, color2.b) ||
!Mathf.Approximately(color1.a, color2.a));
}
public static implicit operator bool(OverlayColorData obj)
{
return ((System.Object)obj) != null;
}
public bool Equals(OverlayColorData other)
{
return (this == other);
}
public override bool Equals(object other)
{
return Equals(other as OverlayColorData);
}
public static bool operator == (OverlayColorData cd1, OverlayColorData cd2)
{
if (cd1)
{
if (cd2)
{
if (cd2.channelMask.Length != cd1.channelMask.Length) return false;
for (int i = 0; i < cd1.channelMask.Length; i++)
{
if (DifferentColor(cd1.channelMask[i], cd2.channelMask[i]))
return false;
}
for (int i = 0; i < cd1.channelAdditiveMask.Length; i++)
{
if (DifferentColor(cd1.channelAdditiveMask[i], cd2.channelAdditiveMask[i]))
return false;
}
return true;
}
return false;
}
return (!(bool)cd2);
}
public static bool operator != (OverlayColorData cd1, OverlayColorData cd2)
{
if (cd1)
{
if (cd2)
{
if (cd2.channelMask.Length != cd1.channelMask.Length) return true;
for (int i = 0; i < cd1.channelMask.Length; i++)
{
if (DifferentColor(cd1.channelMask[i], cd2.channelMask[i]))
return true;
}
for (int i = 0; i < cd1.channelAdditiveMask.Length; i++)
{
if (DifferentColor(cd1.channelAdditiveMask[i], cd2.channelAdditiveMask[i]))
return true;
}
return false;
}
return true;
}
return ((bool)cd2);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public void EnsureChannels(int channels)
{
if (channelMask == null)
{
channelMask = new Color[channels];
channelAdditiveMask = new Color[channels];
for (int i = 0; i < channels; i++)
{
channelMask[i] = Color.white;
channelAdditiveMask[i] = new Color(0, 0, 0, 0);
}
}
else
{
if (channelMask.Length < channels)
{
var newMask = new Color[channels];
System.Array.Copy(channelMask, newMask, channelMask.Length);
for (int i = channelMask.Length; i < channels; i++)
{
newMask[i] = Color.white;
}
channelMask = newMask;
}
if (channelAdditiveMask.Length < channels)
{
var newAdditiveMask = new Color[channels];
System.Array.Copy(channelAdditiveMask, newAdditiveMask, channelAdditiveMask.Length);
for (int i = channelAdditiveMask.Length; i < channels; i++)
{
newAdditiveMask[i] = new Color(0,0,0,0);
}
channelAdditiveMask = newAdditiveMask;
}
}
}
public void AssignTo(OverlayColorData dest)
{
if (name != null)
{
dest.name = String.Copy(name);
}
dest.channelMask = new Color[channelMask.Length];
for (int i = 0; i < channelMask.Length; i++)
{
dest.channelMask[i] = channelMask[i];
}
dest.channelAdditiveMask = new Color[channelAdditiveMask.Length];
for (int i = 0; i < channelAdditiveMask.Length; i++)
{
dest.channelAdditiveMask[i] = channelAdditiveMask[i];
}
}
}
}
| |
// 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.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
public sealed class CmsSigner
{
private static readonly Oid s_defaultAlgorithm = Oid.FromOidValue(Oids.Sha256, OidGroup.HashAlgorithm);
private SubjectIdentifierType _signerIdentifierType;
public X509Certificate2 Certificate { get; set; }
public AsymmetricAlgorithm PrivateKey { get; set; }
public X509Certificate2Collection Certificates { get; private set; } = new X509Certificate2Collection();
public Oid DigestAlgorithm { get; set; }
public X509IncludeOption IncludeOption { get; set; }
public CryptographicAttributeObjectCollection SignedAttributes { get; private set; } = new CryptographicAttributeObjectCollection();
public CryptographicAttributeObjectCollection UnsignedAttributes { get; private set; } = new CryptographicAttributeObjectCollection();
public SubjectIdentifierType SignerIdentifierType
{
get { return _signerIdentifierType; }
set
{
if (value < SubjectIdentifierType.IssuerAndSerialNumber || value > SubjectIdentifierType.NoSignature)
throw new ArgumentException(SR.Format(SR.Cryptography_Cms_Invalid_Subject_Identifier_Type, value));
_signerIdentifierType = value;
}
}
public CmsSigner()
: this(SubjectIdentifierType.IssuerAndSerialNumber, null)
{
}
public CmsSigner(SubjectIdentifierType signerIdentifierType)
: this(signerIdentifierType, null)
{
}
public CmsSigner(X509Certificate2 certificate)
: this(SubjectIdentifierType.IssuerAndSerialNumber, certificate)
{
}
// This can be implemented with netcoreapp20 with the cert creation API.
// * Open the parameters as RSACSP (RSA PKCS#1 signature was hard-coded in netfx)
// * Which will fail on non-Windows
// * Create a certificate with subject CN=CMS Signer Dummy Certificate
// * Need to check against NetFx to find out what the NotBefore/NotAfter values are
// * No extensions
//
// Since it would only work on Windows, it could also be just done as P/Invokes to
// CertCreateSelfSignedCertificate on a split Windows/netstandard implementation.
public CmsSigner(CspParameters parameters) => throw new PlatformNotSupportedException();
public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate) : this(signerIdentifierType, certificate, null)
{
}
public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate, AsymmetricAlgorithm privateKey)
{
switch (signerIdentifierType)
{
case SubjectIdentifierType.Unknown:
_signerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
case SubjectIdentifierType.IssuerAndSerialNumber:
_signerIdentifierType = signerIdentifierType;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
_signerIdentifierType = signerIdentifierType;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
case SubjectIdentifierType.NoSignature:
_signerIdentifierType = signerIdentifierType;
IncludeOption = X509IncludeOption.None;
break;
default:
_signerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
IncludeOption = X509IncludeOption.ExcludeRoot;
break;
}
Certificate = certificate;
DigestAlgorithm = new Oid(s_defaultAlgorithm);
PrivateKey = privateKey;
}
internal void CheckCertificateValue()
{
if (SignerIdentifierType == SubjectIdentifierType.NoSignature)
{
return;
}
if (Certificate == null)
{
throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoSignerCert);
}
if (PrivateKey == null && !Certificate.HasPrivateKey)
{
throw new CryptographicException(SR.Cryptography_Cms_Signing_RequiresPrivateKey);
}
}
internal SignerInfoAsn Sign(
ReadOnlyMemory<byte> data,
string contentTypeOid,
bool silent,
out X509Certificate2Collection chainCerts)
{
HashAlgorithmName hashAlgorithmName = PkcsHelpers.GetDigestAlgorithm(DigestAlgorithm);
IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithmName);
hasher.AppendData(data.Span);
byte[] dataHash = hasher.GetHashAndReset();
SignerInfoAsn newSignerInfo = new SignerInfoAsn();
newSignerInfo.DigestAlgorithm.Algorithm = DigestAlgorithm;
// If the user specified attributes (not null, count > 0) we need attributes.
// If the content type is null we're counter-signing, and need the message digest attr.
// If the content type is otherwise not-data we need to record it as the content-type attr.
if (SignedAttributes?.Count > 0 || contentTypeOid != Oids.Pkcs7Data)
{
List<AttributeAsn> signedAttrs = BuildAttributes(SignedAttributes);
using (var writer = new AsnWriter(AsnEncodingRules.DER))
{
writer.WriteOctetString(dataHash);
signedAttrs.Add(
new AttributeAsn
{
AttrType = new Oid(Oids.MessageDigest, Oids.MessageDigest),
AttrValues = new[] { new ReadOnlyMemory<byte>(writer.Encode()) },
});
}
if (contentTypeOid != null)
{
using (var writer = new AsnWriter(AsnEncodingRules.DER))
{
writer.WriteObjectIdentifier(contentTypeOid);
signedAttrs.Add(
new AttributeAsn
{
AttrType = new Oid(Oids.ContentType, Oids.ContentType),
AttrValues = new[] { new ReadOnlyMemory<byte>(writer.Encode()) },
});
}
}
// Use the serializer/deserializer to DER-normalize the attribute order.
SignedAttributesSet signedAttrsSet = new SignedAttributesSet();
signedAttrsSet.SignedAttributes = PkcsHelpers.NormalizeAttributeSet(
signedAttrs.ToArray(),
normalized => hasher.AppendData(normalized));
// Since this contains user data in a context where BER is permitted, use BER.
// There shouldn't be any observable difference here between BER and DER, though,
// since the top level fields were written by NormalizeSet.
using (AsnWriter attrsWriter = new AsnWriter(AsnEncodingRules.BER))
{
signedAttrsSet.Encode(attrsWriter);
newSignerInfo.SignedAttributes = attrsWriter.Encode();
}
dataHash = hasher.GetHashAndReset();
}
switch (SignerIdentifierType)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
byte[] serial = Certificate.GetSerialNumber();
Array.Reverse(serial);
newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn
{
Issuer = Certificate.IssuerName.RawData,
SerialNumber = serial,
};
newSignerInfo.Version = 1;
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
newSignerInfo.Sid.SubjectKeyIdentifier = PkcsPal.Instance.GetSubjectKeyIdentifier(Certificate);
newSignerInfo.Version = 3;
break;
case SubjectIdentifierType.NoSignature:
newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn
{
Issuer = SubjectIdentifier.DummySignerEncodedValue,
SerialNumber = new byte[1],
};
newSignerInfo.Version = 1;
break;
default:
Debug.Fail($"Unresolved SignerIdentifierType value: {SignerIdentifierType}");
throw new CryptographicException();
}
if (UnsignedAttributes != null && UnsignedAttributes.Count > 0)
{
List<AttributeAsn> attrs = BuildAttributes(UnsignedAttributes);
newSignerInfo.UnsignedAttributes = PkcsHelpers.NormalizeAttributeSet(attrs.ToArray());
}
bool signed;
Oid signatureAlgorithm;
ReadOnlyMemory<byte> signatureValue;
if (SignerIdentifierType == SubjectIdentifierType.NoSignature)
{
signatureAlgorithm = new Oid(Oids.NoSignature, null);
signatureValue = dataHash;
signed = true;
}
else
{
signed = CmsSignature.Sign(
dataHash,
hashAlgorithmName,
Certificate,
PrivateKey,
silent,
out signatureAlgorithm,
out signatureValue);
}
if (!signed)
{
throw new CryptographicException(SR.Cryptography_Cms_CannotDetermineSignatureAlgorithm);
}
newSignerInfo.SignatureValue = signatureValue;
newSignerInfo.SignatureAlgorithm.Algorithm = signatureAlgorithm;
X509Certificate2Collection certs = new X509Certificate2Collection();
certs.AddRange(Certificates);
if (SignerIdentifierType != SubjectIdentifierType.NoSignature)
{
if (IncludeOption == X509IncludeOption.EndCertOnly)
{
certs.Add(Certificate);
}
else if (IncludeOption != X509IncludeOption.None)
{
X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
if (!chain.Build(Certificate))
{
foreach (X509ChainStatus status in chain.ChainStatus)
{
if (status.Status == X509ChainStatusFlags.PartialChain)
{
throw new CryptographicException(SR.Cryptography_Cms_IncompleteCertChain);
}
}
}
X509ChainElementCollection elements = chain.ChainElements;
int count = elements.Count;
int last = count - 1;
if (last == 0)
{
// If there's always one cert treat it as EE, not root.
last = -1;
}
for (int i = 0; i < count; i++)
{
X509Certificate2 cert = elements[i].Certificate;
if (i == last &&
IncludeOption == X509IncludeOption.ExcludeRoot &&
cert.SubjectName.RawData.AsSpan().SequenceEqual(cert.IssuerName.RawData))
{
break;
}
certs.Add(cert);
}
}
}
chainCerts = certs;
return newSignerInfo;
}
internal static List<AttributeAsn> BuildAttributes(CryptographicAttributeObjectCollection attributes)
{
List<AttributeAsn> signedAttrs = new List<AttributeAsn>();
if (attributes == null || attributes.Count == 0)
{
return signedAttrs;
}
foreach (CryptographicAttributeObject attributeObject in attributes)
{
AttributeAsn newAttr = new AttributeAsn
{
AttrType = attributeObject.Oid,
AttrValues = new ReadOnlyMemory<byte>[attributeObject.Values.Count],
};
for (int i = 0; i < attributeObject.Values.Count; i++)
{
newAttr.AttrValues[i] = attributeObject.Values[i].RawData;
}
signedAttrs.Add(newAttr);
}
return signedAttrs;
}
}
}
| |
#if NETCOREAPP3_1
using System;
using System.Linq;
using System.Text;
using System.Buffers;
using System.Reflection;
using System.Buffers.Binary;
using NUnit.Framework;
#if LIGHT_EXPRESSION
using static FastExpressionCompiler.LightExpression.Expression;
namespace FastExpressionCompiler.LightExpression.IssueTests
#else
using static System.Linq.Expressions.Expression;
namespace FastExpressionCompiler.IssueTests
#endif
{
public delegate bool DeserializerDlg<in T>(ref ReadOnlySequence<byte> seq, T value, out long bytesRead);
[TestFixture]
public class Issue237_Trying_to_implement_For_Foreach_loop_but_getting_an_InvalidProgramException_thrown : ITest
{
private static readonly MethodInfo _tryRead = typeof(ReaderExtensions).GetMethod(nameof(ReaderExtensions.TryReadValue));
private static readonly MethodInfo _tryDeserialize = typeof(Serializer).GetMethod(nameof(Serializer.TryDeserializeValues));
public int Run()
{
Conditional_with_Equal_true_should_shortcircuit_to_Brtrue_or_Brfalse();
Conditional_with_Equal_0_should_shortcircuit_to_Brtrue_or_Brfalse();
Conditional_with_Equal_false_should_shortcircuit_to_Brtrue_or_Brfalse();
Conditional_with_NotEqual_true_should_shortcircuit_to_Brtrue_or_Brfalse();
Conditional_with_NotEqual_false_should_shortcircuit_to_Brtrue_or_Brfalse();
Try_compare_strings();
Should_Deserialize_Simple();
Should_Deserialize_Simple_via_manual_CSharp_code();
return 8;
}
[Test]
public void Should_Deserialize_Simple_via_manual_CSharp_code()
{
DeserializerDlg<Word> dlgWord =
/*DeserializerDlg<Word>*/(ref ReadOnlySequence<Byte> input, Word value, out Int64 bytesRead) =>
{
SequenceReader<Byte> reader;
String wordValue;
reader = new SequenceReader<Byte>(input);
if (ReaderExtensions.TryReadValue<String>(
ref reader,
out wordValue) == false)
{
bytesRead = reader.Consumed;
return false;
}
value.Value = wordValue;
bytesRead = reader.Consumed;
return true;
};
DeserializerDlg<Simple> dlgSimple =
/*DeserializerDlg<Simple>*/(ref ReadOnlySequence<Byte> input, Simple value, out Int64 bytesRead) =>
{
SequenceReader<Byte> reader;
Int32 identifier;
Word[] content;
Byte contentLength;
reader = new SequenceReader<Byte>(input);
if (ReaderExtensions.TryReadValue<Int32>(
ref reader,
out identifier) == false)
{
bytesRead = reader.Consumed;
return false;
}
if (ReaderExtensions.TryReadValue<Byte>(
ref reader,
out contentLength) == false)
{
bytesRead = reader.Consumed;
return false;
}
if (Serializer.TryDeserializeValues<Word>(
ref reader,
(Int32)contentLength,
out content) == false)
{
bytesRead = reader.Consumed;
return false;
}
value.Identifier = identifier;
value.Sentence = content;
bytesRead = reader.Consumed;
return true;
};
Serializer.Setup(dlgWord);
Serializer.Setup(dlgSimple);
RunDeserializer();
}
// This is for benchmark
#if !LIGHT_EXPRESSION
public static void CreateExpression_and_CompileSys(
out DeserializerDlg<Word> desWord,
out DeserializerDlg<Simple> desSimple)
{
var reader = Variable(typeof(SequenceReader<byte>), "reader");
var bytesRead = Parameter(typeof(long).MakeByRefType(), "bytesRead");
var input = Parameter(typeof(ReadOnlySequence<byte>).MakeByRefType(), "input");
var createReader = Assign(reader,
New(typeof(SequenceReader<byte>).GetConstructor(new[] { typeof(ReadOnlySequence<byte>) }), input));
var returnTarget = Label(typeof(bool));
var returnLabel = Label(returnTarget, Constant(default(bool)));
var returnFalse =
Block(
Assign(bytesRead,
Property(reader,
typeof(SequenceReader<byte>).GetProperty(nameof(SequenceReader<byte>.Consumed)))),
Block(Return(returnTarget, Constant(false), typeof(bool)), returnLabel));
var returnTrue =
Block(
Assign(bytesRead,
Property(reader,
typeof(SequenceReader<byte>).GetProperty(nameof(SequenceReader<byte>.Consumed)))),
Block(Return(returnTarget, Constant(true), typeof(bool)), returnLabel));
var valueWord = Parameter(typeof(Word), "value");
var wordValueVar = Variable(typeof(string), "wordValue");
var expr0 = Lambda<DeserializerDlg<Word>>(
Block(new[] { reader, wordValueVar },
createReader,
IfThen(
NotEqual(Call(_tryRead.MakeGenericMethod(typeof(string)), reader, wordValueVar), Constant(true)),
returnFalse),
Assign(Property(valueWord, nameof(Word.Value)), wordValueVar),
returnTrue),
input, valueWord, bytesRead);
desWord = expr0.Compile();
var valueSimple = Parameter(typeof(Simple), "value");
var identifierVar = Variable(typeof(int), "identifier");
var contentVar = Variable(typeof(Word[]), "content");
var contentLenVar = Variable(typeof(byte), "contentLength");
var expr1 = Lambda<DeserializerDlg<Simple>>(
Block(new[] { reader, identifierVar, contentVar, contentLenVar },
createReader,
IfThen(
NotEqual(Call(_tryRead.MakeGenericMethod(typeof(int)), reader, identifierVar), Constant(true)),
returnFalse),
IfThen(
NotEqual(Call(_tryRead.MakeGenericMethod(typeof(byte)), reader, contentLenVar), Constant(true)),
returnFalse),
IfThen(
NotEqual(Call(_tryDeserialize.MakeGenericMethod(typeof(Word)), reader, Convert(contentLenVar, typeof(int)), contentVar), Constant(true)),
returnFalse),
Assign(Property(valueSimple, nameof(Simple.Identifier)), identifierVar),
Assign(Property(valueSimple, nameof(Simple.Sentence)), contentVar),
returnTrue),
input, valueSimple, bytesRead);
desSimple = expr1.Compile();
}
#else
public static void CreateLightExpression_and_CompileFast(
out DeserializerDlg<Word> desWord,
out DeserializerDlg<Simple> desSimple)
{
var reader = Variable(typeof(SequenceReader<byte>), "reader");
var bytesRead = Parameter(typeof(long).MakeByRefType(), "bytesRead");
var input = Parameter(typeof(ReadOnlySequence<byte>).MakeByRefType(), "input");
var createReader = Assign(reader,
New(typeof(SequenceReader<byte>).GetConstructor(new[] { typeof(ReadOnlySequence<byte>) }), input));
var returnTarget = Label(typeof(bool));
var returnLabel = Label(returnTarget, Constant(default(bool)));
var returnFalse =
Block(
Assign(bytesRead,
Property(reader,
typeof(SequenceReader<byte>).GetProperty(nameof(SequenceReader<byte>.Consumed)))),
Block(Return(returnTarget, Constant(false), typeof(bool)), returnLabel));
var returnTrue =
Block(
Assign(bytesRead,
Property(reader,
typeof(SequenceReader<byte>).GetProperty(nameof(SequenceReader<byte>.Consumed)))),
Block(Return(returnTarget, Constant(true), typeof(bool)), returnLabel));
var valueWord = Parameter(typeof(Word), "value");
var wordValueVar = Variable(typeof(string), "wordValue");
var expr0 = Lambda<DeserializerDlg<Word>>(
Block(new[] { reader, wordValueVar },
createReader,
IfThen(
NotEqual(Call(_tryRead.MakeGenericMethod(typeof(string)), reader, wordValueVar), Constant(true)),
returnFalse),
Assign(Property(valueWord, nameof(Word.Value)), wordValueVar),
returnTrue),
input, valueWord, bytesRead);
desWord = expr0.CompileFast();
var valueSimple = Parameter(typeof(Simple), "value");
var identifierVar = Variable(typeof(int), "identifier");
var contentVar = Variable(typeof(Word[]), "content");
var contentLenVar = Variable(typeof(byte), "contentLength");
var expr1 = Lambda<DeserializerDlg<Simple>>(
Block(new[] { reader, identifierVar, contentVar, contentLenVar },
createReader,
IfThen(
NotEqual(Call(_tryRead.MakeGenericMethod(typeof(int)), reader, identifierVar), Constant(true)),
returnFalse),
IfThen(
NotEqual(Call(_tryRead.MakeGenericMethod(typeof(byte)), reader, contentLenVar), Constant(true)),
returnFalse),
IfThen(
NotEqual(Call(_tryDeserialize.MakeGenericMethod(typeof(Word)), reader, Convert(contentLenVar, typeof(int)), contentVar), Constant(true)),
returnFalse),
Assign(Property(valueSimple, nameof(Simple.Identifier)), identifierVar),
Assign(Property(valueSimple, nameof(Simple.Sentence)), contentVar),
returnTrue),
input, valueSimple, bytesRead);
desSimple = expr1.CompileFast();
}
#endif
public static bool RunDeserializer(DeserializerDlg<Word> desWord, DeserializerDlg<Simple> desSimple)
{
Serializer.Setup(desWord);
Serializer.Setup(desSimple);
var expected = new Simple
{
Identifier = 150,
Sentence = new[] { new Word { Value = "hello" }, new Word { Value = "there" } }
};
Memory<byte> buffer = new byte[19];
// 4 bytes
BinaryPrimitives.WriteInt32BigEndian(buffer.Span, expected.Identifier);
// 4+=1 byte for word count
buffer.Span.Slice(4)[0] = 2;
// 5+=2 bytes for the 1st word length
BinaryPrimitives.WriteInt16BigEndian(buffer.Span.Slice(5), 5);
// 7+=5 bytes for the 1st word
Encoding.UTF8.GetBytes(expected.Sentence[0].Value, buffer.Span.Slice(7));
// 12+=2 bytes for the 2nd word length
BinaryPrimitives.WriteInt16BigEndian(buffer.Span.Slice(12), 5);
// 14+=5 bytes for the 2nd word
Encoding.UTF8.GetBytes(expected.Sentence[1].Value, buffer.Span.Slice(14));
var deserialized = new Simple();
var input = new ReadOnlySequence<byte>(buffer);
return Serializer.TryDeserialize(ref input, deserialized, out var bytesRead);
}
[Test]
public void Should_Deserialize_Simple()
{
var reader = Variable(typeof(SequenceReader<byte>), "reader");
var bytesRead = Parameter(typeof(long).MakeByRefType(), "bytesRead");
var input = Parameter(typeof(ReadOnlySequence<byte>).MakeByRefType(), "input");
var createReader = Assign(reader,
New(typeof(SequenceReader<byte>).GetConstructor(new[] { typeof(ReadOnlySequence<byte>) }), input));
var returnTarget = Label(typeof(bool));
var returnLabel = Label(returnTarget, Constant(default(bool)));
var returnFalse =
Block(
Assign(bytesRead,
Property(reader,
typeof(SequenceReader<byte>).GetProperty(nameof(SequenceReader<byte>.Consumed)))),
Block(Return(returnTarget, Constant(false), typeof(bool)), returnLabel));
var returnTrue =
Block(
Assign(bytesRead,
Property(reader,
typeof(SequenceReader<byte>).GetProperty(nameof(SequenceReader<byte>.Consumed)))),
Block(Return(returnTarget, Constant(true), typeof(bool)), returnLabel));
var valueWord = Parameter(typeof(Word), "value");
var wordValueVar = Variable(typeof(string), "wordValue");
var expr0 = Lambda<DeserializerDlg<Word>>(
Block(new[] { reader, wordValueVar },
createReader,
IfThen(
NotEqual(Call(_tryRead.MakeGenericMethod(typeof(string)), reader, wordValueVar), Constant(true)),
returnFalse),
Assign(Property(valueWord, nameof(Word.Value)), wordValueVar),
returnTrue),
input, valueWord, bytesRead);
expr0.PrintCSharp();
// sanity check
var f0sys = expr0.CompileSys();
f0sys.PrintIL("system compiled il");
var f0 = expr0.CompileFast(true);
f0.PrintIL();
Serializer.Setup(f0);
var valueSimple = Parameter(typeof(Simple), "value");
var identifierVar = Variable(typeof(int), "identifier");
var contentVar = Variable(typeof(Word[]), "content");
var contentLenVar = Variable(typeof(byte), "contentLength");
var expr1 = Lambda<DeserializerDlg<Simple>>(
Block(new[] { reader, identifierVar, contentVar, contentLenVar },
createReader,
IfThen(
NotEqual(Call(_tryRead.MakeGenericMethod(typeof(int)), reader, identifierVar), Constant(true)),
returnFalse),
IfThen(
NotEqual(Call(_tryRead.MakeGenericMethod(typeof(byte)), reader, contentLenVar), Constant(true)),
returnFalse),
IfThen(
NotEqual(Call(_tryDeserialize.MakeGenericMethod(typeof(Word)), reader, Convert(contentLenVar, typeof(int)), contentVar), Constant(true)),
returnFalse),
Assign(Property(valueSimple, nameof(Simple.Identifier)), identifierVar),
Assign(Property(valueSimple, nameof(Simple.Sentence)), contentVar),
returnTrue),
input, valueSimple, bytesRead);
expr1.PrintCSharp();
var f1sys = expr1.CompileSys();
f1sys.PrintIL("system compiled il");
var f1 = expr1.CompileFast(true);
f1.PrintIL();
Serializer.Setup(f1);
RunDeserializer();
}
public void RunDeserializer()
{
var expected = new Simple
{
Identifier = 150,
Sentence = new[] { new Word { Value = "hello" }, new Word { Value = "there" } }
};
Memory<byte> buffer = new byte[19];
// 4 bytes
BinaryPrimitives.WriteInt32BigEndian(buffer.Span, expected.Identifier);
// 4+=1 byte for word count
buffer.Span.Slice(4)[0] = 2;
// 5+=2 bytes for the 1st word length
BinaryPrimitives.WriteInt16BigEndian(buffer.Span.Slice(5), 5);
// 7+=5 bytes for the 1st word
Encoding.UTF8.GetBytes(expected.Sentence[0].Value, buffer.Span.Slice(7));
// 12+=2 bytes for the 2nd word length
BinaryPrimitives.WriteInt16BigEndian(buffer.Span.Slice(12), 5);
// 14+=5 bytes for the 2nd word
Encoding.UTF8.GetBytes(expected.Sentence[1].Value, buffer.Span.Slice(14));
var deserialized = new Simple();
var input = new ReadOnlySequence<byte>(buffer);
var isDeserialized = Serializer.TryDeserialize(ref input, deserialized, out var bytesRead);
Assert.True(isDeserialized);
Assert.AreEqual(buffer.Length, bytesRead);
Assert.AreEqual(expected, deserialized);
}
[Test]
public void Conditional_with_Equal_true_should_shortcircuit_to_Brtrue_or_Brfalse()
{
var returnTarget = Label(typeof(string));
var returnLabel = Label(returnTarget, Constant(null, typeof(string)));
var returnTrue = Block(
Return(returnTarget, Constant("true"), typeof(string)),
returnLabel);
var returnFalse = Block(
Return(returnTarget, Constant("false"), typeof(string)),
returnLabel);
var boolParam = Parameter(typeof(bool), "b");
var expr = Lambda<Func<bool, string>>(
Block(
IfThen(Equal(boolParam, Constant(true)),
returnTrue),
returnFalse),
boolParam);
expr.PrintCSharp();
var fs = expr.CompileSys();
fs.PrintIL("system compiled il");
Assert.AreEqual("true", fs(true));
Assert.AreEqual("false", fs(false));
var f = expr.CompileFast(true);
f.PrintIL();
Assert.AreEqual("true", f(true));
Assert.AreEqual("false", f(false));
}
[Test]
public void Conditional_with_Equal_0_should_shortcircuit_to_Brtrue_or_Brfalse()
{
var returnTarget = Label(typeof(string));
var returnLabel = Label(returnTarget, Constant(null, typeof(string)));
var returnFalse = Block(Return(returnTarget, Constant("false"), typeof(string)), returnLabel);
var returnTrue = Block(Return(returnTarget, Constant("true"), typeof(string)), returnLabel);
var intParam = Parameter(typeof(int), "n");
var expr = Lambda<Func<int, string>>(
Block(
IfThen(Equal(intParam, Constant(0)),
returnTrue),
returnFalse),
intParam);
var fs = expr.CompileSys();
fs.PrintIL("system compiled il");
var f = expr.CompileFast(true);
Assert.IsNotNull(f);
f.PrintIL();
Assert.AreEqual("true", f(0));
Assert.AreEqual("false", f(42));
}
[Test]
public void Conditional_with_Equal_false_should_shortcircuit_to_Brtrue_or_Brfalse()
{
var returnTarget = Label(typeof(string));
var returnLabel = Label(returnTarget, Constant(null, typeof(string)));
var returnFalse = Block(Return(returnTarget, Constant("false"), typeof(string)), returnLabel);
var returnTrue = Block(Return(returnTarget, Constant("true"), typeof(string)), returnLabel);
var boolParam = Parameter(typeof(bool), "b");
var expr = Lambda<Func<bool, string>>(
Block(
IfThen(Equal(boolParam, Constant(false)),
returnFalse),
returnTrue),
boolParam);
var f = expr.CompileFast(true);
Assert.IsNotNull(f);
f.PrintIL();
Assert.AreEqual("true", f(true));
Assert.AreEqual("false", f(false));
}
[Test]
public void Conditional_with_NotEqual_true_should_shortcircuit_to_Brtrue_or_Brfalse()
{
var returnTarget = Label(typeof(string));
var returnLabel = Label(returnTarget, Constant(null, typeof(string)));
var returnFalse = Block(Return(returnTarget, Constant("false"), typeof(string)), returnLabel);
var returnTrue = Block(Return(returnTarget, Constant("true"), typeof(string)), returnLabel);
var boolParam = Parameter(typeof(bool), "b");
var expr = Lambda<Func<bool, string>>(
Block(
IfThen(NotEqual(boolParam, Constant(true)),
returnFalse),
returnTrue),
boolParam);
var f = expr.CompileFast(true);
Assert.IsNotNull(f);
f.PrintIL();
Assert.AreEqual("true", f(true));
Assert.AreEqual("false", f(false));
}
[Test]
public void Conditional_with_NotEqual_false_should_shortcircuit_to_Brtrue_or_Brfalse()
{
var returnTarget = Label(typeof(string));
var returnLabel = Label(returnTarget, Constant(null, typeof(string)));
var returnFalse = Block(Return(returnTarget, Constant("false"), typeof(string)), returnLabel);
var returnTrue = Block(Return(returnTarget, Constant("true"), typeof(string)), returnLabel);
var boolParam = Parameter(typeof(bool), "b");
var expr = Lambda<Func<bool, string>>(
Block(
IfThen(NotEqual(boolParam, Constant(false)),
returnTrue),
returnFalse),
boolParam);
var f = expr.CompileFast(true);
Assert.IsNotNull(f);
f.PrintIL();
Assert.AreEqual("true", f(true));
Assert.AreEqual("false", f(false));
}
public void Try_compare_strings()
{
var returnTarget = Label(typeof(string));
var returnLabel = Label(returnTarget, Constant(null, typeof(string)));
var returnFalse = Block(Return(returnTarget, Constant("false"), typeof(string)), returnLabel);
var returnTrue = Block(Return(returnTarget, Constant("true"), typeof(string)), returnLabel);
var strParam = Parameter(typeof(string), "s");
var expr = Lambda<Func<string, string>>(
Block(
IfThen(Equal(strParam, Constant("42")),
returnTrue),
returnFalse
),
strParam);
var fs = expr.CompileSys();
fs.PrintIL("system compiled il");
var f = expr.CompileFast(true);
Assert.IsNotNull(f);
f.PrintIL();
Assert.AreEqual("true", f("42"));
Assert.AreEqual("false", f("35"));
}
}
public class Simple
{
public int Identifier { get; set; }
public Word[] Sentence { get; set; }
public override bool Equals(object obj) =>
obj is Simple value
&& value.Identifier == Identifier
&& value.Sentence.SequenceEqual(Sentence);
}
public class Word
{
public string Value { get; set; }
public override bool Equals(object obj) =>
obj is Word w && w.Value == Value;
}
internal struct VarShort
{
public short Value { get; set; }
public VarShort(short value) => Value = value;
}
internal static class Serializer
{
public static bool TryDeserialize<T>(ref ReadOnlySequence<byte> input, T value, out long byteRead) =>
SerializerStorage<T>.TryDeserialize(ref input, value, out byteRead);
public static bool TryDeserializeValues<T>(ref SequenceReader<byte> input, int length, out T[] values) where T : new()
{
if (length == 0)
{
values = Array.Empty<T>();
return true;
}
values = new T[length];
for (var i = 0; i < length; i++)
{
var current = new T();
var b = input.GetRemainingSequence();
if (!TryDeserialize(ref b, current, out var bytesRead))
{
values = Array.Empty<T>();
return false;
}
values[i] = current;
input.Advance(bytesRead);
}
return true;
}
public static void Setup<T>(DeserializerDlg<T> des) =>
SerializerStorage<T>.TryDeserialize = des;
private static class SerializerStorage<T>
{
public static DeserializerDlg<T> TryDeserialize { get; set; }
}
}
internal static class ReaderExtensions
{
public static bool TryReadValue<T>(this ref SequenceReader<byte> reader, out T value) =>
ReaderStorage<T>.TryRead(ref reader, out value);
static ReaderExtensions()
{
ReaderStorage<int>.TryRead = (ref SequenceReader<byte> reader, out int value) =>
reader.TryReadBigEndian(out value);
ReaderStorage<byte>.TryRead = (ref SequenceReader<byte> reader, out byte value) =>
reader.TryRead(out value);
ReaderStorage<string>.TryRead = (ref SequenceReader<byte> reader, out string value) =>
{
value = default;
if (!reader.TryReadBigEndian(out short len)) return false;
var strLen = unchecked((ushort)len);
if (reader.Remaining < strLen) return false;
var strSequence = reader.Sequence.Slice(reader.Position, strLen);
value = strSequence.AsString();
reader.Advance(strLen);
return true;
};
ReaderStorage<VarShort>.TryRead = (ref SequenceReader<byte> reader, out VarShort value) =>
{
var result = 0;
for (var offset = 0; offset < 16; offset += 7)
{
if (!reader.TryRead(out var readByte))
{
value = default;
return false;
}
var hasNext = (readByte & 128) == 128;
if (offset > 0)
result += (readByte & sbyte.MaxValue) << offset;
else
result += (readByte & sbyte.MaxValue);
if (result > short.MaxValue) result -= 65536;
if (!hasNext) break;
}
value = new VarShort((short)result);
return true;
};
}
private static class ReaderStorage<T>
{
public delegate bool TryReadValue(ref SequenceReader<byte> reader, out T value);
public static TryReadValue TryRead { get; set; }
}
}
internal static class SequenceExtensions
{
public static string AsString(this ref ReadOnlySequence<byte> buffer, Encoding useEncoding = default)
{
var encoding = useEncoding ?? Encoding.UTF8;
if (buffer.IsSingleSegment)
return encoding.GetString(buffer.First.Span);
return string.Create((int)buffer.Length, buffer, (span, sequence) =>
{
foreach (var segment in sequence)
{
encoding.GetChars(segment.Span, span);
span = span.Slice(segment.Length);
}
});
}
public static ReadOnlySequence<byte> GetRemainingSequence(this ref SequenceReader<byte> r) =>
r.Sequence.Slice(r.Position);
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace System.Net.NetworkInformation
{
internal class SystemNetworkInterface : NetworkInterface
{
private readonly string _name;
private readonly string _id;
private readonly string _description;
private readonly byte[] _physicalAddress;
private readonly uint _addressLength;
private readonly NetworkInterfaceType _type;
private readonly OperationalStatus _operStatus;
private readonly long _speed;
// Any interface can have two completely different valid indexes for ipv4 and ipv6.
private readonly uint _index = 0;
private readonly uint _ipv6Index = 0;
private readonly Interop.IpHlpApi.AdapterFlags _adapterFlags;
private readonly SystemIPInterfaceProperties _interfaceProperties = null;
internal static int InternalLoopbackInterfaceIndex
{
get
{
return GetBestInterfaceForAddress(IPAddress.Loopback);
}
}
internal static int InternalIPv6LoopbackInterfaceIndex
{
get
{
return GetBestInterfaceForAddress(IPAddress.IPv6Loopback);
}
}
private static int GetBestInterfaceForAddress(IPAddress addr)
{
int index;
Internals.SocketAddress address = new Internals.SocketAddress(addr);
int error = (int)Interop.IpHlpApi.GetBestInterfaceEx(address.Buffer, out index);
if (error != 0)
{
throw new NetworkInformationException(error);
}
return index;
}
internal static bool InternalGetIsNetworkAvailable()
{
try
{
NetworkInterface[] networkInterfaces = GetNetworkInterfaces();
foreach (NetworkInterface netInterface in networkInterfaces)
{
if (netInterface.OperationalStatus == OperationalStatus.Up && netInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel
&& netInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
return true;
}
}
}
catch (NetworkInformationException nie)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exception(NetEventSource.ComponentType.NetworkInformation, "SystemNetworkInterface", "InternalGetIsNetworkAvailable", nie);
}
}
return false;
}
internal static NetworkInterface[] GetNetworkInterfaces()
{
Contract.Ensures(Contract.Result<NetworkInterface[]>() != null);
AddressFamily family = AddressFamily.Unspecified;
uint bufferSize = 0;
SafeLocalAllocHandle buffer = null;
Interop.IpHlpApi.FIXED_INFO fixedInfo = HostInformationPal.GetFixedInfo();
List<SystemNetworkInterface> interfaceList = new List<SystemNetworkInterface>();
Interop.IpHlpApi.GetAdaptersAddressesFlags flags =
Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeGateways
| Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeWins;
// Figure out the right buffer size for the adapter information.
uint result = Interop.IpHlpApi.GetAdaptersAddresses(
family, (uint)flags, IntPtr.Zero, SafeLocalAllocHandle.Zero, ref bufferSize);
while (result == Interop.IpHlpApi.ERROR_BUFFER_OVERFLOW)
{
// Allocate the buffer and get the adapter info.
using (buffer = SafeLocalAllocHandle.LocalAlloc((int)bufferSize))
{
result = Interop.IpHlpApi.GetAdaptersAddresses(
family, (uint)flags, IntPtr.Zero, buffer, ref bufferSize);
// If succeeded, we're going to add each new interface.
if (result == Interop.IpHlpApi.ERROR_SUCCESS)
{
// Linked list of interfaces.
IntPtr ptr = buffer.DangerousGetHandle();
while (ptr != IntPtr.Zero)
{
// Traverse the list, marshal in the native structures, and create new NetworkInterfaces.
Interop.IpHlpApi.IpAdapterAddresses adapterAddresses = Marshal.PtrToStructure<Interop.IpHlpApi.IpAdapterAddresses>(ptr);
interfaceList.Add(new SystemNetworkInterface(fixedInfo, adapterAddresses));
ptr = adapterAddresses.next;
}
}
}
}
// If we don't have any interfaces detected, return empty.
if (result == Interop.IpHlpApi.ERROR_NO_DATA || result == Interop.IpHlpApi.ERROR_INVALID_PARAMETER)
{
return new SystemNetworkInterface[0];
}
// Otherwise we throw on an error.
if (result != Interop.IpHlpApi.ERROR_SUCCESS)
{
throw new NetworkInformationException((int)result);
}
return interfaceList.ToArray();
}
internal SystemNetworkInterface(Interop.IpHlpApi.FIXED_INFO fixedInfo, Interop.IpHlpApi.IpAdapterAddresses ipAdapterAddresses)
{
// Store the common API information.
_id = ipAdapterAddresses.AdapterName;
_name = ipAdapterAddresses.friendlyName;
_description = ipAdapterAddresses.description;
_index = ipAdapterAddresses.index;
_physicalAddress = ipAdapterAddresses.address;
_addressLength = ipAdapterAddresses.addressLength;
_type = ipAdapterAddresses.type;
_operStatus = ipAdapterAddresses.operStatus;
_speed = (long)ipAdapterAddresses.receiveLinkSpeed;
// API specific info.
_ipv6Index = ipAdapterAddresses.ipv6Index;
_adapterFlags = ipAdapterAddresses.flags;
_interfaceProperties = new SystemIPInterfaceProperties(fixedInfo, ipAdapterAddresses);
}
public override string Id { get { return _id; } }
public override string Name { get { return _name; } }
public override string Description { get { return _description; } }
public override PhysicalAddress GetPhysicalAddress()
{
byte[] newAddr = new byte[_addressLength];
// Buffer.BlockCopy only supports int while addressLength is uint (see IpAdapterAddresses).
// Will throw OverflowException if addressLength > Int32.MaxValue.
Buffer.BlockCopy(_physicalAddress, 0, newAddr, 0, checked((int)_addressLength));
return new PhysicalAddress(newAddr);
}
public override NetworkInterfaceType NetworkInterfaceType { get { return _type; } }
public override IPInterfaceProperties GetIPProperties()
{
return _interfaceProperties;
}
public override IPv4InterfaceStatistics GetIPv4Statistics()
{
return new SystemIPv4InterfaceStatistics(_index);
}
public override IPInterfaceStatistics GetIPStatistics()
{
return new SystemIPInterfaceStatistics(_index);
}
public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
{
if (networkInterfaceComponent == NetworkInterfaceComponent.IPv6
&& ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv6Enabled) != 0))
{
return true;
}
if (networkInterfaceComponent == NetworkInterfaceComponent.IPv4
&& ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv4Enabled) != 0))
{
return true;
}
return false;
}
// We cache this to be consistent across all platforms.
public override OperationalStatus OperationalStatus
{
get
{
return _operStatus;
}
}
public override long Speed
{
get
{
return _speed;
}
}
public override bool IsReceiveOnly
{
get
{
return ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.ReceiveOnly) > 0);
}
}
/// <summary>The interface doesn't allow multicast.</summary>
public override bool SupportsMulticast
{
get
{
return ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.NoMulticast) == 0);
}
}
}
}
| |
/* ====================================================================
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 NPOI.OpenXmlFormats.Spreadsheet;
using System;
using NPOI.XSSF.Model;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using NPOI.SS.UserModel;
using System.Collections.Generic;
using NPOI.Util;
using NPOI.SS;
using System.Collections;
namespace NPOI.XSSF.UserModel
{
/**
* High level representation of a row of a spreadsheet.
*/
public class XSSFRow : IRow, IComparable<XSSFRow>
{
private static POILogger _logger = POILogFactory.GetLogger(typeof(XSSFRow));
/**
* the xml bean Containing all cell defInitions for this row
*/
private CT_Row _row;
/**
* Cells of this row keyed by their column indexes.
* The TreeMap ensures that the cells are ordered by columnIndex in the ascending order.
*/
private SortedDictionary<int, ICell> _cells;
/**
* the parent sheet
*/
private XSSFSheet _sheet;
/**
* Construct a XSSFRow.
*
* @param row the xml bean Containing all cell defInitions for this row.
* @param sheet the parent sheet.
*/
public XSSFRow(CT_Row row, XSSFSheet sheet)
{
_row = row;
_sheet = sheet;
_cells = new SortedDictionary<int, ICell>();
if (0 < row.SizeOfCArray())
{
foreach (CT_Cell c in row.c)
{
XSSFCell cell = new XSSFCell(this, c);
_cells.Add(cell.ColumnIndex,cell);
sheet.OnReadCell(cell);
}
}
}
/**
* Returns the XSSFSheet this row belongs to
*
* @return the XSSFSheet that owns this row
*/
public ISheet Sheet
{
get
{
return this._sheet;
}
}
/**
* Cell iterator over the physically defined cells:
* <blockquote><pre>
* for (Iterator<Cell> it = row.cellIterator(); it.HasNext(); ) {
* Cell cell = it.next();
* ...
* }
* </pre></blockquote>
*
* @return an iterator over cells in this row.
*/
public SortedDictionary<int, ICell>.ValueCollection.Enumerator CellIterator()
{
return _cells.Values.GetEnumerator();
}
/**
* Alias for {@link #cellIterator()} to allow foreach loops:
* <blockquote><pre>
* for(Cell cell : row){
* ...
* }
* </pre></blockquote>
*
* @return an iterator over cells in this row.
*/
public IEnumerator<ICell> GetEnumerator()
{
return CellIterator();
}
/**
* Compares two <code>XSSFRow</code> objects. Two rows are equal if they belong to the same worksheet and
* their row indexes are Equal.
*
* @param row the <code>XSSFRow</code> to be Compared.
* @return the value <code>0</code> if the row number of this <code>XSSFRow</code> is
* equal to the row number of the argument <code>XSSFRow</code>; a value less than
* <code>0</code> if the row number of this this <code>XSSFRow</code> is numerically less
* than the row number of the argument <code>XSSFRow</code>; and a value greater
* than <code>0</code> if the row number of this this <code>XSSFRow</code> is numerically
* greater than the row number of the argument <code>XSSFRow</code>.
* @throws ArgumentException if the argument row belongs to a different worksheet
*/
public int CompareTo(XSSFRow row)
{
int thisVal = this.RowNum;
if (row.Sheet != Sheet)
throw new ArgumentException("The Compared rows must belong to the same XSSFSheet");
int anotherVal = row.RowNum;
return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1));
}
/**
* Use this to create new cells within the row and return it.
* <p>
* The cell that is returned is a {@link Cell#CELL_TYPE_BLANK}. The type can be Changed
* either through calling <code>SetCellValue</code> or <code>SetCellType</code>.
* </p>
* @param columnIndex - the column number this cell represents
* @return Cell a high level representation of the Created cell.
* @throws ArgumentException if columnIndex < 0 or greater than 16384,
* the maximum number of columns supported by the SpreadsheetML format (.xlsx)
*/
public ICell CreateCell(int columnIndex)
{
return CreateCell(columnIndex, CellType.Blank);
}
/**
* Use this to create new cells within the row and return it.
*
* @param columnIndex - the column number this cell represents
* @param type - the cell's data type
* @return XSSFCell a high level representation of the Created cell.
* @throws ArgumentException if the specified cell type is invalid, columnIndex < 0
* or greater than 16384, the maximum number of columns supported by the SpreadsheetML format (.xlsx)
* @see Cell#CELL_TYPE_BLANK
* @see Cell#CELL_TYPE_BOOLEAN
* @see Cell#CELL_TYPE_ERROR
* @see Cell#CELL_TYPE_FORMULA
* @see Cell#CELL_TYPE_NUMERIC
* @see Cell#CELL_TYPE_STRING
*/
public ICell CreateCell(int columnIndex, CellType type)
{
CT_Cell ctCell;
XSSFCell prev = _cells.ContainsKey(columnIndex) ? (XSSFCell)_cells[columnIndex] : null;
if (prev != null)
{
ctCell = prev.GetCTCell();
ctCell.Set(new CT_Cell());
}
else
{
ctCell = _row.AddNewC();
}
XSSFCell xcell = new XSSFCell(this, ctCell);
xcell.SetCellNum(columnIndex);
if (type != CellType.Blank)
{
xcell.SetCellType(type);
}
_cells[columnIndex] = xcell;
return xcell;
}
/**
* Returns the cell at the given (0 based) index,
* with the {@link NPOI.SS.usermodel.Row.MissingCellPolicy} from the parent Workbook.
*
* @return the cell at the given (0 based) index
*/
public ICell GetCell(int cellnum)
{
return GetCell(cellnum, _sheet.Workbook.MissingCellPolicy);
}
/// <summary>
/// Get the hssfcell representing a given column (logical cell)
/// 0-based. If you ask for a cell that is not defined, then
/// you Get a null.
/// This is the basic call, with no policies applied
/// </summary>
/// <param name="cellnum">0 based column number</param>
/// <returns>Cell representing that column or null if Undefined.</returns>
private ICell RetrieveCell(int cellnum)
{
if (!_cells.ContainsKey(cellnum))
return null;
//if (cellnum < 0 || cellnum >= cells.Count) return null;
return _cells[cellnum];
}
/**
* Returns the cell at the given (0 based) index, with the specified {@link NPOI.SS.usermodel.Row.MissingCellPolicy}
*
* @return the cell at the given (0 based) index
* @throws ArgumentException if cellnum < 0 or the specified MissingCellPolicy is invalid
* @see Row#RETURN_NULL_AND_BLANK
* @see Row#RETURN_BLANK_AS_NULL
* @see Row#CREATE_NULL_AS_BLANK
*/
public ICell GetCell(int cellnum, MissingCellPolicy policy)
{
if (cellnum < 0) throw new ArgumentException("Cell index must be >= 0");
XSSFCell cell = (XSSFCell)RetrieveCell(cellnum);
if (policy == MissingCellPolicy.RETURN_NULL_AND_BLANK)
{
return cell;
}
if (policy == MissingCellPolicy.RETURN_BLANK_AS_NULL)
{
if (cell == null) return cell;
if (cell.CellType == CellType.Blank)
{
return null;
}
return cell;
}
if (policy == MissingCellPolicy.CREATE_NULL_AS_BLANK)
{
if (cell == null)
{
return CreateCell(cellnum, CellType.Blank);
}
return cell;
}
throw new ArgumentException("Illegal policy " + policy + " (" + policy.id + ")");
}
int GetFirstKey(SortedDictionary<int, ICell>.KeyCollection keys)
{
int i = 0;
foreach (int key in keys)
{
if (i == 0)
return key;
}
throw new ArgumentOutOfRangeException();
}
int GetLastKey(SortedDictionary<int, ICell>.KeyCollection keys)
{
int i = 0;
foreach (int key in keys)
{
if (i == keys.Count - 1)
return key;
i++;
}
throw new ArgumentOutOfRangeException();
}
/**
* Get the number of the first cell Contained in this row.
*
* @return short representing the first logical cell in the row,
* or -1 if the row does not contain any cells.
*/
public short FirstCellNum
{
get
{
return (short)(_cells.Count == 0 ? -1 : GetFirstKey(_cells.Keys));
}
}
/**
* Gets the index of the last cell Contained in this row <b>PLUS ONE</b>. The result also
* happens to be the 1-based column number of the last cell. This value can be used as a
* standard upper bound when iterating over cells:
* <pre>
* short minColIx = row.GetFirstCellNum();
* short maxColIx = row.GetLastCellNum();
* for(short colIx=minColIx; colIx<maxColIx; colIx++) {
* XSSFCell cell = row.GetCell(colIx);
* if(cell == null) {
* continue;
* }
* //... do something with cell
* }
* </pre>
*
* @return short representing the last logical cell in the row <b>PLUS ONE</b>,
* or -1 if the row does not contain any cells.
*/
public short LastCellNum
{
get
{
return (short)(_cells.Count == 0 ? -1 : (GetLastKey(_cells.Keys) + 1));
}
}
/**
* Get the row's height measured in twips (1/20th of a point). If the height is not Set, the default worksheet value is returned,
* See {@link NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints()}
*
* @return row height measured in twips (1/20th of a point)
*/
public short Height
{
get
{
return (short)(HeightInPoints * 20);
}
set
{
if (value < 0)
{
if (_row.IsSetHt()) _row.unSetHt();
if (_row.IsSetCustomHeight()) _row.unSetCustomHeight();
}
else
{
_row.ht = ((double)value / 20);
_row.customHeight = (true);
}
}
}
/**
* Returns row height measured in point size. If the height is not Set, the default worksheet value is returned,
* See {@link NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints()}
*
* @return row height measured in point size
* @see NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints()
*/
public float HeightInPoints
{
get
{
if (this._row.IsSetHt())
{
return (float)this._row.ht;
}
return _sheet.DefaultRowHeightInPoints;
}
set
{
this.Height = (short)(value == -1 ? -1 : (value * 20));
}
}
/**
* Gets the number of defined cells (NOT number of cells in the actual row!).
* That is to say if only columns 0,4,5 have values then there would be 3.
*
* @return int representing the number of defined cells in the row.
*/
public int PhysicalNumberOfCells
{
get
{
return _cells.Count;
}
}
/**
* Get row number this row represents
*
* @return the row number (0 based)
*/
public int RowNum
{
get
{
return (int)_row.r-1;
}
set
{
int maxrow = SpreadsheetVersion.EXCEL2007.LastRowIndex;
if (value < 0 || value > maxrow)
{
throw new ArgumentException("Invalid row number (" + value
+ ") outside allowable range (0.." + maxrow + ")");
}
_row.r = (uint)(value+1);
}
}
/**
* Get whether or not to display this row with 0 height
*
* @return - height is zero or not.
*/
public bool ZeroHeight
{
get
{
return (bool)this._row.hidden;
}
set
{
this._row.hidden = value;
}
}
/**
* Is this row formatted? Most aren't, but some rows
* do have whole-row styles. For those that do, you
* can get the formatting from {@link #GetRowStyle()}
*/
public bool IsFormatted
{
get
{
return _row.IsSetS();
}
}
/**
* Returns the whole-row cell style. Most rows won't
* have one of these, so will return null. Call
* {@link #isFormatted()} to check first.
*/
public ICellStyle RowStyle
{
get
{
if (!IsFormatted) return null;
StylesTable stylesSource = ((XSSFWorkbook)Sheet.Workbook).GetStylesSource();
if (stylesSource.NumCellStyles > 0)
{
return stylesSource.GetStyleAt((int)_row.s);
}
else
{
return null;
}
}
set
{
if (value == null)
{
if (_row.IsSetS())
{
_row.UnsetS();
_row.UnsetCustomFormat();
}
}
else
{
StylesTable styleSource = ((XSSFWorkbook)Sheet.Workbook).GetStylesSource();
XSSFCellStyle xStyle = (XSSFCellStyle)value;
xStyle.VerifyBelongsToStylesSource(styleSource);
long idx = styleSource.PutStyle(xStyle);
_row.s = (uint)idx;
_row.customFormat = (true);
}
}
}
/**
* Applies a whole-row cell styling to the row.
* If the value is null then the style information is Removed,
* causing the cell to used the default workbook style.
*/
public void SetRowStyle(ICellStyle style)
{
}
/**
* Remove the Cell from this row.
*
* @param cell the cell to remove
*/
public void RemoveCell(ICell cell)
{
if (cell.Row != this)
{
throw new ArgumentException("Specified cell does not belong to this row");
}
XSSFCell xcell = (XSSFCell)cell;
if (xcell.IsPartOfArrayFormulaGroup)
{
xcell.NotifyArrayFormulaChanging();
}
if (cell.CellType == CellType.Formula)
{
((XSSFWorkbook)_sheet.Workbook).OnDeleteFormula(xcell);
}
_cells.Remove(cell.ColumnIndex);
}
/**
* Returns the underlying CT_Row xml bean Containing all cell defInitions in this row
*
* @return the underlying CT_Row xml bean
*/
public CT_Row GetCTRow()
{
return _row;
}
/**
* Fired when the document is written to an output stream.
*
* @see NPOI.XSSF.usermodel.XSSFSheet#Write(java.io.OutputStream) ()
*/
internal void OnDocumentWrite()
{
// check if cells in the CT_Row are ordered
bool isOrdered = true;
if (_row.SizeOfCArray() != _cells.Count) isOrdered = false;
else
{
int i = 0;
foreach (XSSFCell cell in _cells.Values)
{
CT_Cell c1 = cell.GetCTCell();
CT_Cell c2 = _row.GetCArray(i++);
String r1 = c1.r;
String r2 = c2.r;
if (!(r1 == null ? r2 == null : r1.Equals(r2)))
{
isOrdered = false;
break;
}
}
}
if (!isOrdered)
{
CT_Cell[] cArray = new CT_Cell[_cells.Count];
int i = 0;
foreach (XSSFCell c in _cells.Values)
{
cArray[i++] = c.GetCTCell();
}
_row.SetCArray(cArray);
}
}
/**
* @return formatted xml representation of this row
*/
public override String ToString()
{
return _row.ToString();
}
/**
* update cell references when Shifting rows
*
* @param n the number of rows to move
*/
internal void Shift(int n)
{
int rownum = RowNum + n;
CalculationChain calcChain = ((XSSFWorkbook)_sheet.Workbook).GetCalculationChain();
int sheetId = (int)_sheet.sheet.sheetId;
String msg = "Row[rownum=" + RowNum + "] contains cell(s) included in a multi-cell array formula. " +
"You cannot change part of an array.";
foreach (ICell c in this)
{
XSSFCell cell = (XSSFCell)c;
if (cell.IsPartOfArrayFormulaGroup)
{
cell.NotifyArrayFormulaChanging(msg);
}
//remove the reference in the calculation chain
if (calcChain != null)
calcChain.RemoveItem(sheetId, cell.GetReference());
CT_Cell CT_Cell = cell.GetCTCell();
String r = new CellReference(rownum, cell.ColumnIndex).FormatAsString();
CT_Cell.r = r;
}
RowNum = rownum;
}
#region IRow Members
public List<ICell> Cells
{
get {
List<ICell> cells = new List<ICell>();
foreach (ICell cell in _cells.Values)
{
cells.Add(cell);
}
return cells; }
}
public void MoveCell(ICell cell, int newColumn)
{
throw new NotImplementedException();
}
public IRow CopyRowTo(int targetIndex)
{
return this.Sheet.CopyRow(this.RowNum, targetIndex);
}
public ICell CopyCell(int sourceIndex, int targetIndex)
{
return CellUtil.CopyCell(this, sourceIndex, targetIndex);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public int OutlineLevel
{
get
{
return _row.outlineLevel;
}
}
#endregion
}
}
| |
using Docker.DotNet;
using Docker.DotNet.Models;
using reexmonkey.xmisc.core.system.net.extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace reexmonkey.xmisc.backbone.virtualization.docker.extensions
{
public static class DockerDotNetExtensions
{
public static DockerClient CreateDockerClient(string endpoint)
=> new DockerClientConfiguration(new Uri(endpoint)).CreateClient();
public static DockerClient CreateDockerClient(string address, int port)
=> new DockerClientConfiguration(new Uri($"{address}:{port}")).CreateClient();
public static DockerClient CreateDockerClient(IPEndPoint endPoint)
=> new DockerClientConfiguration(new Uri(endPoint.ToString())).CreateClient();
public static Task<CreateContainerResponse> CreateContainerAsync(
this DockerClient client,
string image,
string name,
int hostPort,
int containerPort,
string protocol,
IEnumerable<string> env,
CancellationToken cancellation = default)
{
var key = containerPort.Format(protocol);
var exposedPorts = new Dictionary<string, EmptyStruct>()
{
{ key, new EmptyStruct() }
};
var portBindings = new Dictionary<string, IList<PortBinding>>()
{
{ key, new List<PortBinding> { new PortBinding() { HostPort = hostPort.ToString() } }}
};
return client.CreateContainerAsync(image, name, env, exposedPorts, portBindings, cancellation);
}
public static Task<CreateContainerResponse> CreateContainerAsync(
this DockerClient client,
string image,
int hostPort,
int containerPort,
string protocol,
IEnumerable<string> env,
CancellationToken cancellation = default)
{
var key = containerPort.Format(protocol);
var exposedPorts = new Dictionary<string, EmptyStruct>()
{
{ key, new EmptyStruct() }
};
var portBindings = new Dictionary<string, IList<PortBinding>>()
{
{ key, new List<PortBinding> { new PortBinding() { HostPort = hostPort.ToString() } }}
};
return client.CreateContainerAsync(image, env, exposedPorts, portBindings, cancellation);
}
public static async Task<CreateContainerResponse> CreateContainerAsync(
this DockerClient client,
string image,
IEnumerable<string> env,
IDictionary<string, EmptyStruct> exposedPorts,
IDictionary<string, IList<PortBinding>> portBindings,
CancellationToken cancellation = default)
{
var parameters = new CreateContainerParameters()
{
Image = image,
Env = env != null ? new List<string>(env) : new List<string>(),
ExposedPorts = exposedPorts != null ? exposedPorts : new Dictionary<string, EmptyStruct>(),
HostConfig = new HostConfig()
{
PortBindings = portBindings != null ? portBindings : new Dictionary<string, IList<PortBinding>>()
}
};
return await client.Containers.CreateContainerAsync(parameters, cancellation).ConfigureAwait(false);
}
public static async Task<CreateContainerResponse> CreateContainerAsync(
this DockerClient client,
string image,
string name,
IEnumerable<string> env,
IDictionary<string, EmptyStruct> exposedPorts,
IDictionary<string, IList<PortBinding>> portBindings,
CancellationToken cancellation = default)
{
var parameters = new CreateContainerParameters()
{
Image = image,
Name = name,
Env = env != null ? new List<string>(env) : new List<string>(),
ExposedPorts = exposedPorts != null ? exposedPorts : new Dictionary<string, EmptyStruct>(),
HostConfig = new HostConfig()
{
PortBindings = portBindings != null ? portBindings : new Dictionary<string, IList<PortBinding>>()
}
};
return await client.Containers.CreateContainerAsync(parameters, cancellation).ConfigureAwait(false);
}
public static async Task<(string id, bool success)> StartContainerAsync(
this DockerClient client,
string containerId,
ContainerStartParameters parameters, CancellationToken cancellation = default)
{
var started = await client.Containers.StartContainerAsync(containerId, parameters, cancellation).ConfigureAwait(false);
return (containerId, started);
}
public static async Task<(string id, bool success)> StartContainerAsync(
this DockerClient client,
string containerId,
ContainerStartParameters parameters,
int delay,
CancellationToken cancellation = default)
{
var result = await client.StartContainerAsync(containerId, parameters, cancellation).ConfigureAwait(false);
await Task.Delay(delay, cancellation).ConfigureAwait(false);
return result;
}
public static bool IsRunning(this ContainerListResponse container)
=> container.State.Equals("running", StringComparison.OrdinalIgnoreCase);
public static async Task<IList<(string id, bool success)>> StartContainersAsync(
this DockerClient client,
IEnumerable<string> containerIds,
ContainerStartParameters parameters,
CancellationToken cancellation = default)
{
var results = new List<(string id, bool success)>();
foreach (var containerId in containerIds)
{
var result = await client.StartContainerAsync(containerId, parameters, cancellation).ConfigureAwait(false);
results.Add(result);
}
return results;
}
public static async Task<(string id, bool success)> StopContainerAsync(
this DockerClient client,
string containerId,
ContainerStopParameters parameters,
CancellationToken cancellation = default)
{
var stopped = await client.Containers.StopContainerAsync(containerId, parameters, cancellation).ConfigureAwait(false);
return (containerId, stopped);
}
public static async Task<IList<(string id, bool success)>> StopContainersAsync(
this DockerClient client,
IEnumerable<string> containerIds,
ContainerStopParameters parameters,
CancellationToken cancellation = default)
{
var results = new List<(string id, bool success)>();
foreach (var containerId in containerIds)
{
var result = await client.StopContainerAsync(containerId, parameters, cancellation).ConfigureAwait(false);
results.Add(result);
}
return results;
}
public static async Task<IList<string>> StopAndRemoveContainersAsync(
this DockerClient client,
IEnumerable<string> containerIds,
ContainerStopParameters stopParameters,
ContainerRemoveParameters removeParameters,
CancellationToken cancellation = default)
{
var results = new List<string>();
var stoppedResults = await client.StopContainersAsync(containerIds, stopParameters, cancellation).ConfigureAwait(false);
//remove stopped containers
foreach (var result in stoppedResults)
{
var removed = await client.RemoveContainerAsync(result.id, removeParameters, cancellation).ConfigureAwait(false);
results.Add(removed);
}
return results;
}
public static async Task<string> RemoveContainerAsync(
this DockerClient client, string id,
ContainerRemoveParameters parameters,
CancellationToken cancellation = default)
{
await client.Containers.RemoveContainerAsync(id, parameters, cancellation).ConfigureAwait(false);
return id;
}
public static async Task<IList<string>> RemoveContainersAsync(
this DockerClient client,
IEnumerable<string> ids,
ContainerRemoveParameters parameters,
CancellationToken cancellation = default)
{
var removed = new List<string>();
foreach (var containerId in ids)
{
var result = await client.RemoveContainerAsync(containerId, parameters, cancellation).ConfigureAwait(false);
if (!removed.Contains(containerId, StringComparer.OrdinalIgnoreCase)) removed.Add(result);
}
return removed;
}
public static Task<IList<ContainerListResponse>> GetContainersAsync(
this DockerClient client,
ContainersListParameters parameters,
CancellationToken cancellation = default)
=> client.Containers.ListContainersAsync(parameters, cancellation);
public static ContainerListResponse FindContainerById(this IEnumerable<ContainerListResponse> containers, string id)
{
return containers.FindContainer(x => x.ID.Equals(id, StringComparison.OrdinalIgnoreCase));
}
public static ContainerListResponse FindContainerByNameAsync(this IEnumerable<ContainerListResponse> containers, string name)
=> containers.FindContainer(x => x.Names.Contains(name, StringComparer.OrdinalIgnoreCase) || x.Names.Contains("/" + name, StringComparer.OrdinalIgnoreCase));
public static ContainerListResponse FindContainerByImageId(this IEnumerable<ContainerListResponse> containers, string imageId)
=> containers.FindContainer(x => x.ImageID.Equals(imageId, StringComparison.OrdinalIgnoreCase));
public static ContainerListResponse FindContainerByImage(this IEnumerable<ContainerListResponse> containers, string image)
=> containers.FindContainer(x => x.Image.Equals(image, StringComparison.OrdinalIgnoreCase));
public static ContainerListResponse FindContainer(this IEnumerable<ContainerListResponse> containers, Func<ContainerListResponse, bool> predicate)
=> containers.FirstOrDefault(predicate);
public static IEnumerable<ContainerListResponse> FindContainersByImageId(this IEnumerable<ContainerListResponse> containers, string imageId)
=> containers.Where(x => x.ImageID.Equals(imageId, StringComparison.OrdinalIgnoreCase));
public static bool Contains(this string source, string other, StringComparison comparison) => source.IndexOf(other, comparison) >= 0;
public static IEnumerable<ContainerListResponse> FindContainersByName(this IEnumerable<ContainerListResponse> containers, string name)
=> containers.Where(x => x.Names.Contains(name, StringComparer.OrdinalIgnoreCase) || x.Names.Contains("/" + name, StringComparer.OrdinalIgnoreCase));
public static IEnumerable<ContainerListResponse> FindContainersByImage(this IEnumerable<ContainerListResponse> containers, string image)
=> containers.Where(x => x.Image.Contains(image, StringComparison.OrdinalIgnoreCase));
public static IEnumerable<ContainerListResponse> FindContainers(this IEnumerable<ContainerListResponse> containers, Func<ContainerListResponse, bool> predicate)
=> containers.Where(predicate);
}
}
| |
// 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.Net;
using System.Text.RegularExpressions;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Users;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays.Changelog
{
public class ChangelogEntry : FillFlowContainer
{
private readonly APIChangelogEntry entry;
[Resolved]
private OsuColour colours { get; set; }
[Resolved]
private OverlayColourProvider colourProvider { get; set; }
private FontUsage fontLarge;
private FontUsage fontMedium;
public ChangelogEntry(APIChangelogEntry entry)
{
this.entry = entry;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Direction = FillDirection.Vertical;
}
[BackgroundDependencyLoader]
private void load()
{
fontLarge = OsuFont.GetFont(size: 16);
fontMedium = OsuFont.GetFont(size: 12);
Children = new[]
{
createTitle(),
createMessage()
};
}
private Drawable createTitle()
{
var entryColour = entry.Major ? colours.YellowLight : Color4.White;
LinkFlowContainer title;
var titleContainer = new Container
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Margin = new MarginPadding { Vertical = 5 },
Children = new Drawable[]
{
new SpriteIcon
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreRight,
Size = new Vector2(10),
Icon = getIconForChangelogEntry(entry.Type),
Colour = entryColour.Opacity(0.5f),
Margin = new MarginPadding { Right = 5 },
},
title = new LinkFlowContainer
{
Direction = FillDirection.Full,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
TextAnchor = Anchor.BottomLeft,
}
}
};
title.AddText(entry.Title, t =>
{
t.Font = fontLarge;
t.Colour = entryColour;
});
if (!string.IsNullOrEmpty(entry.Repository))
addRepositoryReference(title, entryColour);
if (entry.GithubUser != null)
addGithubAuthorReference(title, entryColour);
return titleContainer;
}
private void addRepositoryReference(LinkFlowContainer title, Color4 entryColour)
{
title.AddText(" (", t =>
{
t.Font = fontLarge;
t.Colour = entryColour;
});
title.AddLink($"{entry.Repository.Replace("ppy/", "")}#{entry.GithubPullRequestId}", entry.GithubUrl,
t =>
{
t.Font = fontLarge;
t.Colour = entryColour;
});
title.AddText(")", t =>
{
t.Font = fontLarge;
t.Colour = entryColour;
});
}
private void addGithubAuthorReference(LinkFlowContainer title, Color4 entryColour)
{
title.AddText("by ", t =>
{
t.Font = fontMedium;
t.Colour = entryColour;
t.Padding = new MarginPadding { Left = 10 };
});
if (entry.GithubUser.UserId != null)
{
title.AddUserLink(new User
{
Username = entry.GithubUser.OsuUsername,
Id = entry.GithubUser.UserId.Value
}, t =>
{
t.Font = fontMedium;
t.Colour = entryColour;
});
}
else if (entry.GithubUser.GithubUrl != null)
{
title.AddLink(entry.GithubUser.DisplayName, entry.GithubUser.GithubUrl, t =>
{
t.Font = fontMedium;
t.Colour = entryColour;
});
}
else
{
title.AddText(entry.GithubUser.DisplayName, t =>
{
t.Font = fontMedium;
t.Colour = entryColour;
});
}
}
private Drawable createMessage()
{
if (string.IsNullOrEmpty(entry.MessageHtml))
return Empty();
var message = new TextFlowContainer
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
};
// todo: use markdown parsing once API returns markdown
message.AddText(WebUtility.HtmlDecode(Regex.Replace(entry.MessageHtml, @"<(.|\n)*?>", string.Empty)), t =>
{
t.Font = fontMedium;
t.Colour = colourProvider.Foreground1;
});
return message;
}
private static IconUsage getIconForChangelogEntry(ChangelogEntryType entryType)
{
// compare: https://github.com/ppy/osu-web/blob/master/resources/assets/coffee/react/_components/changelog-entry.coffee#L8-L11
switch (entryType)
{
case ChangelogEntryType.Add:
return FontAwesome.Solid.Plus;
case ChangelogEntryType.Fix:
return FontAwesome.Solid.Check;
case ChangelogEntryType.Misc:
return FontAwesome.Regular.Circle;
default:
throw new ArgumentOutOfRangeException(nameof(entryType), $"Unrecognised entry type {entryType}");
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
The MIT License (MIT)
Copyright (c) 2014 Samuel Neff
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.
https://github.com/samuelneff/MimeTypeMap
*/
using System;
using System.Collections.Generic;
using System.Linq;
namespace ASC.Mail.Utils
{
public static class MimeTypeMap
{
private static readonly Lazy<IDictionary<string, string>> Mappings = new Lazy<IDictionary<string, string>>(BuildMappings);
private static IDictionary<string, string> BuildMappings()
{
var mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {
#region Big freaking list of mime types
// maps both ways,
// extension -> mime type
// and
// mime type -> extension
//
// any mime types on left side not pre-loaded on right side, are added automatically
// some mime types can map to multiple extensions, so to get a deterministic mapping,
// add those to the dictionary specifcially
//
// combination of values from Windows 7 Registry and
// from C:\Windows\System32\inetsrv\config\applicationHost.config
// some added, including .7z and .dat
//
// Some added based on http://www.iana.org/assignments/media-types/media-types.xhtml
// which lists mime types, but not extensions
//
{".323", "text/h323"},
{".3g2", "video/3gpp2"},
{".3gp", "video/3gpp"},
{".3gp2", "video/3gpp2"},
{".3gpp", "video/3gpp"},
{".7z", "application/x-7z-compressed"},
{".aa", "audio/audible"},
{".AAC", "audio/aac"},
{".aaf", "application/octet-stream"},
{".aax", "audio/vnd.audible.aax"},
{".ac3", "audio/ac3"},
{".aca", "application/octet-stream"},
{".accda", "application/msaccess.addin"},
{".accdb", "application/msaccess"},
{".accdc", "application/msaccess.cab"},
{".accde", "application/msaccess"},
{".accdr", "application/msaccess.runtime"},
{".accdt", "application/msaccess"},
{".accdw", "application/msaccess.webapplication"},
{".accft", "application/msaccess.ftemplate"},
{".acx", "application/internet-property-stream"},
{".AddIn", "text/xml"},
{".ade", "application/msaccess"},
{".adobebridge", "application/x-bridge-url"},
{".adp", "application/msaccess"},
{".ADT", "audio/vnd.dlna.adts"},
{".ADTS", "audio/aac"},
{".afm", "application/octet-stream"},
{".ai", "application/postscript"},
{".aif", "audio/aiff"},
{".aifc", "audio/aiff"},
{".aiff", "audio/aiff"},
{".air", "application/vnd.adobe.air-application-installer-package+zip"},
{".amc", "application/mpeg"},
{".anx", "application/annodex"},
{".apk", "application/vnd.android.package-archive" },
{".application", "application/x-ms-application"},
{".art", "image/x-jg"},
{".asa", "application/xml"},
{".asax", "application/xml"},
{".ascx", "application/xml"},
{".asd", "application/octet-stream"},
{".asf", "video/x-ms-asf"},
{".ashx", "application/xml"},
{".asi", "application/octet-stream"},
{".asm", "text/plain"},
{".asmx", "application/xml"},
{".aspx", "application/xml"},
{".asr", "video/x-ms-asf"},
{".asx", "video/x-ms-asf"},
{".atom", "application/atom+xml"},
{".au", "audio/basic"},
{".avi", "video/x-msvideo"},
{".axa", "audio/annodex"},
{".axs", "application/olescript"},
{".axv", "video/annodex"},
{".bas", "text/plain"},
{".bcpio", "application/x-bcpio"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".cab", "application/octet-stream"},
{".caf", "audio/x-caf"},
{".calx", "application/vnd.ms-office.calx"},
{".cat", "application/vnd.ms-pki.seccat"},
{".cc", "text/plain"},
{".cd", "text/plain"},
{".cdda", "audio/aiff"},
{".cdf", "application/x-cdf"},
{".cer", "application/x-x509-ca-cert"},
{".cfg", "text/plain"},
{".chm", "application/octet-stream"},
{".class", "application/x-java-applet"},
{".clp", "application/x-msclip"},
{".cmd", "text/plain"},
{".cmx", "image/x-cmx"},
{".cnf", "text/plain"},
{".cod", "image/cis-cod"},
{".config", "application/xml"},
{".contact", "text/x-ms-contact"},
{".coverage", "application/xml"},
{".cpio", "application/x-cpio"},
{".cpp", "text/plain"},
{".crd", "application/x-mscardfile"},
{".crl", "application/pkix-crl"},
{".crt", "application/x-x509-ca-cert"},
{".cs", "text/plain"},
{".csdproj", "text/plain"},
{".csh", "application/x-csh"},
{".csproj", "text/plain"},
{".css", "text/css"},
{".csv", "text/csv"},
{".cur", "application/octet-stream"},
{".cxx", "text/plain"},
{".dat", "application/octet-stream"},
{".datasource", "application/xml"},
{".dbproj", "text/plain"},
{".dcr", "application/x-director"},
{".def", "text/plain"},
{".deploy", "application/octet-stream"},
{".der", "application/x-x509-ca-cert"},
{".dgml", "application/xml"},
{".dib", "image/bmp"},
{".dif", "video/x-dv"},
{".dir", "application/x-director"},
{".disco", "text/xml"},
{".divx", "video/divx"},
{".dll", "application/x-msdownload"},
{".dll.config", "text/xml"},
{".dlm", "text/dlm"},
{".doc", "application/msword"},
{".docm", "application/vnd.ms-word.document.macroEnabled.12"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".dot", "application/msword"},
{".dotm", "application/vnd.ms-word.template.macroEnabled.12"},
{".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{".dsp", "application/octet-stream"},
{".dsw", "text/plain"},
{".dtd", "text/xml"},
{".dtsConfig", "text/xml"},
{".dv", "video/x-dv"},
{".dvi", "application/x-dvi"},
{".dwf", "drawing/x-dwf"},
{".dwp", "application/octet-stream"},
{".dxr", "application/x-director"},
{".eml", "message/rfc822"},
{".emz", "application/octet-stream"},
{".eot", "application/vnd.ms-fontobject"},
{".eps", "application/postscript"},
{".etl", "application/etl"},
{".etx", "text/x-setext"},
{".evy", "application/envoy"},
{".exe", "application/octet-stream"},
{".exe.config", "text/xml"},
{".fdf", "application/vnd.fdf"},
{".fif", "application/fractals"},
{".filters", "application/xml"},
{".fla", "application/octet-stream"},
{".flac", "audio/flac"},
{".flr", "x-world/x-vrml"},
{".flv", "video/x-flv"},
{".fsscript", "application/fsharp-script"},
{".fsx", "application/fsharp-script"},
{".generictest", "application/xml"},
{".gif", "image/gif"},
{".group", "text/x-ms-group"},
{".gsm", "audio/x-gsm"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".hdf", "application/x-hdf"},
{".hdml", "text/x-hdml"},
{".hhc", "application/x-oleobject"},
{".hhk", "application/octet-stream"},
{".hhp", "application/octet-stream"},
{".hlp", "application/winhlp"},
{".hpp", "text/plain"},
{".hqx", "application/mac-binhex40"},
{".hta", "application/hta"},
{".htc", "text/x-component"},
{".htm", "text/html"},
{".html", "text/html"},
{".htt", "text/webviewhtml"},
{".hxa", "application/xml"},
{".hxc", "application/xml"},
{".hxd", "application/octet-stream"},
{".hxe", "application/xml"},
{".hxf", "application/xml"},
{".hxh", "application/octet-stream"},
{".hxi", "application/octet-stream"},
{".hxk", "application/xml"},
{".hxq", "application/octet-stream"},
{".hxr", "application/octet-stream"},
{".hxs", "application/octet-stream"},
{".hxt", "text/html"},
{".hxv", "application/xml"},
{".hxw", "application/octet-stream"},
{".hxx", "text/plain"},
{".i", "text/plain"},
{".ico", "image/x-icon"},
{".ics", "application/octet-stream"},
{".idl", "text/plain"},
{".ief", "image/ief"},
{".iii", "application/x-iphone"},
{".inc", "text/plain"},
{".inf", "application/octet-stream"},
{".ini", "text/plain"},
{".inl", "text/plain"},
{".ins", "application/x-internet-signup"},
{".ipa", "application/x-itunes-ipa"},
{".ipg", "application/x-itunes-ipg"},
{".ipproj", "text/plain"},
{".ipsw", "application/x-itunes-ipsw"},
{".iqy", "text/x-ms-iqy"},
{".isp", "application/x-internet-signup"},
{".ite", "application/x-itunes-ite"},
{".itlp", "application/x-itunes-itlp"},
{".itms", "application/x-itunes-itms"},
{".itpc", "application/x-itunes-itpc"},
{".IVF", "video/x-ivf"},
{".jar", "application/java-archive"},
{".java", "application/octet-stream"},
{".jck", "application/liquidmotion"},
{".jcz", "application/liquidmotion"},
{".jfif", "image/pjpeg"},
{".jnlp", "application/x-java-jnlp-file"},
{".jpb", "application/octet-stream"},
{".jpe", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/javascript"},
{".json", "application/json"},
{".jsx", "text/jscript"},
{".jsxbin", "text/plain"},
{".latex", "application/x-latex"},
{".library-ms", "application/windows-library+xml"},
{".lit", "application/x-ms-reader"},
{".loadtest", "application/xml"},
{".lpk", "application/octet-stream"},
{".lsf", "video/x-la-asf"},
{".lst", "text/plain"},
{".lsx", "video/x-la-asf"},
{".lzh", "application/octet-stream"},
{".m13", "application/x-msmediaview"},
{".m14", "application/x-msmediaview"},
{".m1v", "video/mpeg"},
{".m2t", "video/vnd.dlna.mpeg-tts"},
{".m2ts", "video/vnd.dlna.mpeg-tts"},
{".m2v", "video/mpeg"},
{".m3u", "audio/x-mpegurl"},
{".m3u8", "audio/x-mpegurl"},
{".m4a", "audio/m4a"},
{".m4b", "audio/m4b"},
{".m4p", "audio/m4p"},
{".m4r", "audio/x-m4r"},
{".m4v", "video/x-m4v"},
{".mac", "image/x-macpaint"},
{".mak", "text/plain"},
{".man", "application/x-troff-man"},
{".manifest", "application/x-ms-manifest"},
{".map", "text/plain"},
{".master", "application/xml"},
{".mda", "application/msaccess"},
{".mdb", "application/x-msaccess"},
{".mde", "application/msaccess"},
{".mdp", "application/octet-stream"},
{".me", "application/x-troff-me"},
{".mfp", "application/x-shockwave-flash"},
{".mht", "message/rfc822"},
{".mhtml", "message/rfc822"},
{".mid", "audio/mid"},
{".midi", "audio/mid"},
{".mix", "application/octet-stream"},
{".mk", "text/plain"},
{".mmf", "application/x-smaf"},
{".mno", "text/xml"},
{".mny", "application/x-msmoney"},
{".mod", "video/mpeg"},
{".mov", "video/quicktime"},
{".movie", "video/x-sgi-movie"},
{".mp2", "video/mpeg"},
{".mp2v", "video/mpeg"},
{".mp3", "audio/mpeg"},
{".mp4", "video/mp4"},
{".mp4v", "video/mp4"},
{".mpa", "video/mpeg"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpf", "application/vnd.ms-mediapackage"},
{".mpg", "video/mpeg"},
{".mpp", "application/vnd.ms-project"},
{".mpv2", "video/mpeg"},
{".mqv", "video/quicktime"},
{".ms", "application/x-troff-ms"},
{".msi", "application/octet-stream"},
{".mso", "application/octet-stream"},
{".mts", "video/vnd.dlna.mpeg-tts"},
{".mtx", "application/xml"},
{".mvb", "application/x-msmediaview"},
{".mvc", "application/x-miva-compiled"},
{".mxp", "application/x-mmxp"},
{".nc", "application/x-netcdf"},
{".nsc", "video/x-ms-asf"},
{".nws", "message/rfc822"},
{".ocx", "application/octet-stream"},
{".oda", "application/oda"},
{".odb", "application/vnd.oasis.opendocument.database"},
{".odc", "application/vnd.oasis.opendocument.chart"},
{".odf", "application/vnd.oasis.opendocument.formula"},
{".odg", "application/vnd.oasis.opendocument.graphics"},
{".odh", "text/plain"},
{".odi", "application/vnd.oasis.opendocument.image"},
{".odl", "text/plain"},
{".odm", "application/vnd.oasis.opendocument.text-master"},
{".odp", "application/vnd.oasis.opendocument.presentation"},
{".ods", "application/vnd.oasis.opendocument.spreadsheet"},
{".odt", "application/vnd.oasis.opendocument.text"},
{".oga", "audio/ogg"},
{".ogg", "audio/ogg"},
{".ogv", "video/ogg"},
{".ogx", "application/ogg"},
{".one", "application/onenote"},
{".onea", "application/onenote"},
{".onepkg", "application/onenote"},
{".onetmp", "application/onenote"},
{".onetoc", "application/onenote"},
{".onetoc2", "application/onenote"},
{".opus", "audio/ogg"},
{".orderedtest", "application/xml"},
{".osdx", "application/opensearchdescription+xml"},
{".otf", "application/font-sfnt"},
{".otg", "application/vnd.oasis.opendocument.graphics-template"},
{".oth", "application/vnd.oasis.opendocument.text-web"},
{".otp", "application/vnd.oasis.opendocument.presentation-template"},
{".ots", "application/vnd.oasis.opendocument.spreadsheet-template"},
{".ott", "application/vnd.oasis.opendocument.text-template"},
{".oxt", "application/vnd.openofficeorg.extension"},
{".p10", "application/pkcs10"},
{".p12", "application/x-pkcs12"},
{".p7b", "application/x-pkcs7-certificates"},
{".p7c", "application/pkcs7-mime"},
{".p7m", "application/pkcs7-mime"},
{".p7r", "application/x-pkcs7-certreqresp"},
{".p7s", "application/pkcs7-signature"},
{".pbm", "image/x-portable-bitmap"},
{".pcast", "application/x-podcast"},
{".pct", "image/pict"},
{".pcx", "application/octet-stream"},
{".pcz", "application/octet-stream"},
{".pdf", "application/pdf"},
{".pfb", "application/octet-stream"},
{".pfm", "application/octet-stream"},
{".pfx", "application/x-pkcs12"},
{".pgm", "image/x-portable-graymap"},
{".pic", "image/pict"},
{".pict", "image/pict"},
{".pkgdef", "text/plain"},
{".pkgundef", "text/plain"},
{".pko", "application/vnd.ms-pki.pko"},
{".pls", "audio/scpls"},
{".pma", "application/x-perfmon"},
{".pmc", "application/x-perfmon"},
{".pml", "application/x-perfmon"},
{".pmr", "application/x-perfmon"},
{".pmw", "application/x-perfmon"},
{".png", "image/png"},
{".pnm", "image/x-portable-anymap"},
{".pnt", "image/x-macpaint"},
{".pntg", "image/x-macpaint"},
{".pnz", "image/png"},
{".pot", "application/vnd.ms-powerpoint"},
{".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
{".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
{".ppa", "application/vnd.ms-powerpoint"},
{".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{".ppm", "image/x-portable-pixmap"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prf", "application/pics-rules"},
{".prm", "application/octet-stream"},
{".prx", "application/octet-stream"},
{".ps", "application/postscript"},
{".psc1", "application/PowerShell"},
{".psd", "application/octet-stream"},
{".psess", "application/xml"},
{".psm", "application/octet-stream"},
{".psp", "application/octet-stream"},
{".pub", "application/x-mspublisher"},
{".pwz", "application/vnd.ms-powerpoint"},
{".qht", "text/x-html-insertion"},
{".qhtm", "text/x-html-insertion"},
{".qt", "video/quicktime"},
{".qti", "image/x-quicktime"},
{".qtif", "image/x-quicktime"},
{".qtl", "application/x-quicktimeplayer"},
{".qxd", "application/octet-stream"},
{".ra", "audio/x-pn-realaudio"},
{".ram", "audio/x-pn-realaudio"},
{".rar", "application/x-rar-compressed"},
{".ras", "image/x-cmu-raster"},
{".rat", "application/rat-file"},
{".rc", "text/plain"},
{".rc2", "text/plain"},
{".rct", "text/plain"},
{".rdlc", "application/xml"},
{".reg", "text/plain"},
{".resx", "application/xml"},
{".rf", "image/vnd.rn-realflash"},
{".rgb", "image/x-rgb"},
{".rgs", "text/plain"},
{".rm", "application/vnd.rn-realmedia"},
{".rmi", "audio/mid"},
{".rmp", "application/vnd.rn-rn_music_package"},
{".roff", "application/x-troff"},
{".rpm", "audio/x-pn-realaudio-plugin"},
{".rqy", "text/x-ms-rqy"},
{".rtf", "application/rtf"},
{".rtx", "text/richtext"},
{".ruleset", "application/xml"},
{".s", "text/plain"},
{".safariextz", "application/x-safari-safariextz"},
{".scd", "application/x-msschedule"},
{".scr", "text/plain"},
{".sct", "text/scriptlet"},
{".sd2", "audio/x-sd2"},
{".sdp", "application/sdp"},
{".sea", "application/octet-stream"},
{".searchConnector-ms", "application/windows-search-connector+xml"},
{".setpay", "application/set-payment-initiation"},
{".setreg", "application/set-registration-initiation"},
{".settings", "application/xml"},
{".sgimb", "application/x-sgimb"},
{".sgml", "text/sgml"},
{".sh", "application/x-sh"},
{".shar", "application/x-shar"},
{".shtml", "text/html"},
{".sit", "application/x-stuffit"},
{".sitemap", "application/xml"},
{".skin", "application/xml"},
{".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"},
{".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
{".slk", "application/vnd.ms-excel"},
{".sln", "text/plain"},
{".slupkg-ms", "application/x-ms-license"},
{".smd", "audio/x-smd"},
{".smi", "application/octet-stream"},
{".smx", "audio/x-smd"},
{".smz", "audio/x-smd"},
{".snd", "audio/basic"},
{".snippet", "application/xml"},
{".snp", "application/octet-stream"},
{".sol", "text/plain"},
{".sor", "text/plain"},
{".spc", "application/x-pkcs7-certificates"},
{".spl", "application/futuresplash"},
{".spx", "audio/ogg"},
{".src", "application/x-wais-source"},
{".srf", "text/plain"},
{".SSISDeploymentManifest", "text/xml"},
{".ssm", "application/streamingmedia"},
{".sst", "application/vnd.ms-pki.certstore"},
{".stl", "application/vnd.ms-pki.stl"},
{".sv4cpio", "application/x-sv4cpio"},
{".sv4crc", "application/x-sv4crc"},
{".svc", "application/xml"},
{".svg", "image/svg+xml"},
{".swf", "application/x-shockwave-flash"},
{".t", "application/x-troff"},
{".tar", "application/x-tar"},
{".tcl", "application/x-tcl"},
{".testrunconfig", "application/xml"},
{".testsettings", "application/xml"},
{".tex", "application/x-tex"},
{".texi", "application/x-texinfo"},
{".texinfo", "application/x-texinfo"},
{".tgz", "application/x-compressed"},
{".thmx", "application/vnd.ms-officetheme"},
{".thn", "application/octet-stream"},
{".tif", "image/tiff"},
{".tiff", "image/tiff"},
{".tlh", "text/plain"},
{".tli", "text/plain"},
{".toc", "application/octet-stream"},
{".tr", "application/x-troff"},
{".trm", "application/x-msterminal"},
{".trx", "application/xml"},
{".ts", "video/vnd.dlna.mpeg-tts"},
{".tsv", "text/tab-separated-values"},
{".ttf", "application/font-sfnt"},
{".tts", "video/vnd.dlna.mpeg-tts"},
{".txt", "text/plain"},
{".u32", "application/octet-stream"},
{".uls", "text/iuls"},
{".user", "text/plain"},
{".ustar", "application/x-ustar"},
{".vb", "text/plain"},
{".vbdproj", "text/plain"},
{".vbk", "video/mpeg"},
{".vbproj", "text/plain"},
{".vbs", "text/vbscript"},
{".vcf", "text/x-vcard"},
{".vcproj", "application/xml"},
{".vcs", "text/plain"},
{".vcxproj", "application/xml"},
{".vddproj", "text/plain"},
{".vdp", "text/plain"},
{".vdproj", "text/plain"},
{".vdx", "application/vnd.ms-visio.viewer"},
{".vml", "text/xml"},
{".vscontent", "application/xml"},
{".vsct", "text/xml"},
{".vsd", "application/vnd.visio"},
{".vsi", "application/ms-vsi"},
{".vsix", "application/vsix"},
{".vsixlangpack", "text/xml"},
{".vsixmanifest", "text/xml"},
{".vsmdi", "application/xml"},
{".vspscc", "text/plain"},
{".vss", "application/vnd.visio"},
{".vsscc", "text/plain"},
{".vssettings", "text/xml"},
{".vssscc", "text/plain"},
{".vst", "application/vnd.visio"},
{".vstemplate", "text/xml"},
{".vsto", "application/x-ms-vsto"},
{".vsw", "application/vnd.visio"},
{".vsx", "application/vnd.visio"},
{".vtx", "application/vnd.visio"},
{".wav", "audio/wav"},
{".wave", "audio/wav"},
{".wax", "audio/x-ms-wax"},
{".wbk", "application/msword"},
{".wbmp", "image/vnd.wap.wbmp"},
{".wcm", "application/vnd.ms-works"},
{".wdb", "application/vnd.ms-works"},
{".wdp", "image/vnd.ms-photo"},
{".webarchive", "application/x-safari-webarchive"},
{".webm", "video/webm"},
{".webp", "image/webp"}, /* https://en.wikipedia.org/wiki/WebP */
{".webtest", "application/xml"},
{".wiq", "application/xml"},
{".wiz", "application/msword"},
{".wks", "application/vnd.ms-works"},
{".WLMP", "application/wlmoviemaker"},
{".wlpginstall", "application/x-wlpg-detect"},
{".wlpginstall3", "application/x-wlpg3-detect"},
{".wm", "video/x-ms-wm"},
{".wma", "audio/x-ms-wma"},
{".wmd", "application/x-ms-wmd"},
{".wmf", "application/x-msmetafile"},
{".wml", "text/vnd.wap.wml"},
{".wmlc", "application/vnd.wap.wmlc"},
{".wmls", "text/vnd.wap.wmlscript"},
{".wmlsc", "application/vnd.wap.wmlscriptc"},
{".wmp", "video/x-ms-wmp"},
{".wmv", "video/x-ms-wmv"},
{".wmx", "video/x-ms-wmx"},
{".wmz", "application/x-ms-wmz"},
{".woff", "application/font-woff"},
{".wpl", "application/vnd.ms-wpl"},
{".wps", "application/vnd.ms-works"},
{".wri", "application/x-mswrite"},
{".wrl", "x-world/x-vrml"},
{".wrz", "x-world/x-vrml"},
{".wsc", "text/scriptlet"},
{".wsdl", "text/xml"},
{".wvx", "video/x-ms-wvx"},
{".x", "application/directx"},
{".xaf", "x-world/x-vrml"},
{".xaml", "application/xaml+xml"},
{".xap", "application/x-silverlight-app"},
{".xbap", "application/x-ms-xbap"},
{".xbm", "image/x-xbitmap"},
{".xdr", "text/plain"},
{".xht", "application/xhtml+xml"},
{".xhtml", "application/xhtml+xml"},
{".xla", "application/vnd.ms-excel"},
{".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
{".xlc", "application/vnd.ms-excel"},
{".xld", "application/vnd.ms-excel"},
{".xlk", "application/vnd.ms-excel"},
{".xll", "application/vnd.ms-excel"},
{".xlm", "application/vnd.ms-excel"},
{".xls", "application/vnd.ms-excel"},
{".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".xlt", "application/vnd.ms-excel"},
{".xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
{".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{".xlw", "application/vnd.ms-excel"},
{".xml", "text/xml"},
{".xmta", "application/xml"},
{".xof", "x-world/x-vrml"},
{".XOML", "text/plain"},
{".xpm", "image/x-xpixmap"},
{".xps", "application/vnd.ms-xpsdocument"},
{".xrm-ms", "text/xml"},
{".xsc", "application/xml"},
{".xsd", "text/xml"},
{".xsf", "text/xml"},
{".xsl", "text/xml"},
{".xslt", "text/xml"},
{".xsn", "application/octet-stream"},
{".xss", "application/xml"},
{".xspf", "application/xspf+xml"},
{".xtp", "application/octet-stream"},
{".xwd", "image/x-xwindowdump"},
{".z", "application/x-compress"},
{".zip", "application/zip"},
{"application/fsharp-script", ".fsx"},
{"application/msaccess", ".adp"},
{"application/msword", ".doc"},
{"application/octet-stream", ".bin"},
{"application/onenote", ".one"},
{"application/postscript", ".eps"},
{"application/vnd.ms-excel", ".xls"},
{"application/vnd.ms-powerpoint", ".ppt"},
{"application/vnd.ms-works", ".wks"},
{"application/vnd.visio", ".vsd"},
{"application/x-director", ".dir"},
{"application/x-shockwave-flash", ".swf"},
{"application/x-x509-ca-cert", ".cer"},
{"application/x-zip-compressed", ".zip"},
{"application/xhtml+xml", ".xhtml"},
{"application/xml", ".xml"}, // anomoly, .xml -> text/xml, but application/xml -> many thingss, but all are xml, so safest is .xml
{"audio/aac", ".AAC"},
{"audio/aiff", ".aiff"},
{"audio/basic", ".snd"},
{"audio/mid", ".midi"},
{"audio/wav", ".wav"},
{"audio/x-mpegurl", ".m3u"},
{"audio/x-pn-realaudio", ".ra"},
{"audio/x-smd", ".smd"},
{"image/bmp", ".bmp"},
{"image/jpeg", ".jpg"},
{"image/pict", ".pic"},
{"image/png", ".png"},
{"image/tiff", ".tiff"},
{"image/x-macpaint", ".mac"},
{"image/x-quicktime", ".qti"},
{"message/rfc822", ".eml"},
{"text/html", ".html"},
{"text/plain", ".txt"},
{"text/scriptlet", ".wsc"},
{"text/xml", ".xml"},
{"video/3gpp", ".3gp"},
{"video/3gpp2", ".3gp2"},
{"video/mp4", ".mp4"},
{"video/mpeg", ".mpg"},
{"video/quicktime", ".mov"},
{"video/vnd.dlna.mpeg-tts", ".m2t"},
{"video/x-dv", ".dv"},
{"video/x-la-asf", ".lsf"},
{"video/x-ms-asf", ".asf"},
{"x-world/x-vrml", ".xof"},
#endregion
};
var cache = mappings.ToList(); // need ToList() to avoid modifying while still enumerating
foreach (var mapping in cache)
{
if (!mappings.ContainsKey(mapping.Value))
{
mappings.Add(mapping.Value, mapping.Key);
}
}
return mappings;
}
public static string GetMimeType(string extension)
{
if (extension == null)
{
throw new ArgumentNullException("extension");
}
if (!extension.StartsWith("."))
{
extension = "." + extension;
}
string mime;
return Mappings.Value.TryGetValue(extension, out mime) ? mime : "application/octet-stream";
}
public static string GetExtension(string mimeType)
{
if (mimeType == null)
{
throw new ArgumentNullException("mimeType");
}
if (mimeType.StartsWith("."))
{
throw new ArgumentException("Requested mime type is not valid: " + mimeType);
}
string extension;
if (Mappings.Value.TryGetValue(mimeType, out extension))
{
return extension;
}
throw new ArgumentException("Requested mime type is not registered: " + mimeType);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using NUnit.Framework;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using TestUtil = Lucene.Net.Util.TestUtil;
/// <summary>
/// Simple test that adds numeric terms, where each term has the
/// totalTermFreq of its integer value, and checks that the totalTermFreq is correct.
/// </summary>
// TODO: somehow factor this with BagOfPostings? its almost the same
[TestFixture]
public class TestBagOfPositions : LuceneTestCase // at night this makes like 200k/300k docs and will make Direct's heart beat!
// Lucene3x doesnt have totalTermFreq, so the test isn't interesting there.
{
[Test]
public virtual void Test()
{
IList<string> postingsList = new List<string>();
int numTerms = AtLeast(300);
int maxTermsPerDoc = TestUtil.NextInt(Random(), 10, 20);
bool isSimpleText = "SimpleText".Equals(TestUtil.GetPostingsFormat("field"));
IndexWriterConfig iwc = NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
if ((isSimpleText || iwc.MergePolicy is MockRandomMergePolicy) && (TEST_NIGHTLY || RANDOM_MULTIPLIER > 1))
{
// Otherwise test can take way too long (> 2 hours)
numTerms /= 2;
}
if (VERBOSE)
{
Console.WriteLine("maxTermsPerDoc=" + maxTermsPerDoc);
Console.WriteLine("numTerms=" + numTerms);
}
for (int i = 0; i < numTerms; i++)
{
string term = Convert.ToString(i);
for (int j = 0; j < i; j++)
{
postingsList.Add(term);
}
}
postingsList = CollectionsHelper.Shuffle(postingsList);
ConcurrentQueue<string> postings = new ConcurrentQueue<string>(postingsList);
Directory dir = NewFSDirectory(CreateTempDir(GetFullMethodName()));
RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwc);
int threadCount = TestUtil.NextInt(Random(), 1, 5);
if (VERBOSE)
{
Console.WriteLine("config: " + iw.w.Config);
Console.WriteLine("threadCount=" + threadCount);
}
Field prototype = NewTextField("field", "", Field.Store.NO);
FieldType fieldType = new FieldType((FieldType)prototype.FieldType());
if (Random().NextBoolean())
{
fieldType.OmitNorms = true;
}
int options = Random().Next(3);
if (options == 0)
{
fieldType.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS; // we dont actually need positions
fieldType.StoreTermVectors = true; // but enforce term vectors when we do this so we check SOMETHING
}
else if (options == 1 && !DoesntSupportOffsets.Contains(TestUtil.GetPostingsFormat("field")))
{
fieldType.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
}
// else just positions
ThreadClass[] threads = new ThreadClass[threadCount];
CountdownEvent startingGun = new CountdownEvent(1);
for (int threadID = 0; threadID < threadCount; threadID++)
{
Random threadRandom = new Random(Random().Next());
Document document = new Document();
Field field = new Field("field", "", fieldType);
document.Add(field);
threads[threadID] = new ThreadAnonymousInnerClassHelper(this, numTerms, maxTermsPerDoc, postings, iw, startingGun, threadRandom, document, field);
threads[threadID].Start();
}
startingGun.Signal();
foreach (ThreadClass t in threads)
{
t.Join();
}
iw.ForceMerge(1);
DirectoryReader ir = iw.Reader;
Assert.AreEqual(1, ir.Leaves.Count);
AtomicReader air = (AtomicReader)ir.Leaves[0].Reader;
Terms terms = air.Terms("field");
// numTerms-1 because there cannot be a term 0 with 0 postings:
Assert.AreEqual(numTerms - 1, terms.Size());
TermsEnum termsEnum = terms.Iterator(null);
BytesRef termBR;
while ((termBR = termsEnum.Next()) != null)
{
int value = Convert.ToInt32(termBR.Utf8ToString());
Assert.AreEqual(value, termsEnum.TotalTermFreq());
// don't really need to check more than this, as CheckIndex
// will verify that totalTermFreq == total number of positions seen
// from a docsAndPositionsEnum.
}
ir.Dispose();
iw.Dispose();
dir.Dispose();
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private readonly TestBagOfPositions OuterInstance;
private int NumTerms;
private int MaxTermsPerDoc;
private ConcurrentQueue<string> Postings;
private RandomIndexWriter Iw;
private CountdownEvent StartingGun;
private Random ThreadRandom;
private Document Document;
private Field Field;
public ThreadAnonymousInnerClassHelper(TestBagOfPositions outerInstance, int numTerms, int maxTermsPerDoc, ConcurrentQueue<string> postings, RandomIndexWriter iw, CountdownEvent startingGun, Random threadRandom, Document document, Field field)
{
this.OuterInstance = outerInstance;
this.NumTerms = numTerms;
this.MaxTermsPerDoc = maxTermsPerDoc;
this.Postings = postings;
this.Iw = iw;
this.StartingGun = startingGun;
this.ThreadRandom = threadRandom;
this.Document = document;
this.Field = field;
}
public override void Run()
{
try
{
StartingGun.Wait();
while (!(Postings.Count == 0))
{
StringBuilder text = new StringBuilder();
int numTerms = ThreadRandom.Next(MaxTermsPerDoc);
for (int i = 0; i < numTerms; i++)
{
string token;
if (!Postings.TryDequeue(out token))
{
break;
}
text.Append(' ');
text.Append(token);
}
Field.StringValue = text.ToString();
Iw.AddDocument(Document);
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.