context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H11_City_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="H11_City_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="H10_City"/> collection.
/// </remarks>
[Serializable]
public partial class H11_City_ReChild : BusinessBase<H11_City_ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name");
/// <summary>
/// Gets or sets the CityRoads Child Name.
/// </summary>
/// <value>The CityRoads Child Name.</value>
public string City_Child_Name
{
get { return GetProperty(City_Child_NameProperty); }
set { SetProperty(City_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H11_City_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H11_City_ReChild"/> object.</returns>
internal static H11_City_ReChild NewH11_City_ReChild()
{
return DataPortal.CreateChild<H11_City_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="H11_City_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="city_ID2">The City_ID2 parameter of the H11_City_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="H11_City_ReChild"/> object.</returns>
internal static H11_City_ReChild GetH11_City_ReChild(int city_ID2)
{
return DataPortal.FetchChild<H11_City_ReChild>(city_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H11_City_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H11_City_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="H11_City_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H11_City_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="city_ID2">The City ID2.</param>
protected void Child_Fetch(int city_ID2)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetH11_City_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID2", city_ID2).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, city_ID2);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="H11_City_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(City_Child_NameProperty, dr.GetString("City_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="H11_City_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H10_City parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddH11_City_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H11_City_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(H10_City parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateH11_City_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="H11_City_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(H10_City parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteH11_City_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID2", parent.City_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.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 VehicleStatisticsApi.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;
}
}
}
| |
//
// PlaylistSource.cs
//
// Authors:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2005-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;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.Data;
using Hyena.Data.Sqlite;
using Hyena.Collections;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.Database;
using Banshee.Sources;
using Banshee.Collection;
using Banshee.Collection.Database;
namespace Banshee.Playlist
{
public class PlaylistSource : AbstractPlaylistSource, IUnmapableSource
{
private static HyenaSqliteCommand add_track_range_command;
private static HyenaSqliteCommand add_track_command;
private static HyenaSqliteCommand remove_track_range_command;
private static string add_track_range_from_joined_model_sql;
private static string generic_name = Catalog.GetString ("Playlist");
protected override string SourceTable {
get { return "CorePlaylists"; }
}
protected override string SourcePrimaryKey {
get { return "PlaylistID"; }
}
protected override string TrackJoinTable {
get { return "CorePlaylistEntries"; }
}
protected long MaxViewOrder {
get {
return ServiceManager.DbConnection.Query<long> (
"SELECT MAX(ViewOrder) + 1 FROM CorePlaylistEntries WHERE PlaylistID = ?", DbId);
}
}
static PlaylistSource ()
{
add_track_range_command = new HyenaSqliteCommand (@"
INSERT INTO CorePlaylistEntries
(EntryID, PlaylistID, TrackID, ViewOrder)
SELECT null, ?, ItemID, OrderId + ?
FROM CoreCache WHERE ModelID = ?
LIMIT ?, ?"
);
add_track_command = new HyenaSqliteCommand (@"
INSERT INTO CorePlaylistEntries
(EntryID, PlaylistID, TrackID, ViewOrder)
VALUES (null, ?, ?, ?)"
);
add_track_range_from_joined_model_sql = @"
INSERT INTO CorePlaylistEntries
(EntryID, PlaylistID, TrackID, ViewOrder)
SELECT null, ?, TrackID, OrderId + ?
FROM CoreCache c INNER JOIN {0} e ON c.ItemID = e.{1}
WHERE ModelID = ?
LIMIT ?, ?";
remove_track_range_command = new HyenaSqliteCommand (@"
DELETE FROM CorePlaylistEntries WHERE PlaylistID = ? AND
EntryID IN (SELECT ItemID FROM CoreCache
WHERE ModelID = ? LIMIT ?, ?)"
);
}
#region Constructors
public PlaylistSource (string name, PrimarySource parent) : base (generic_name, name, parent)
{
SetProperties ();
}
protected PlaylistSource (string name, int dbid, PrimarySource parent) : this (name, dbid, -1, 0, parent, 0, false)
{
}
protected PlaylistSource (string name, int dbid, int sortColumn, int sortType, PrimarySource parent, int count, bool is_temp)
: base (generic_name, name, dbid, sortColumn, sortType, parent, is_temp)
{
SetProperties ();
SavedCount = count;
}
#endregion
private void SetProperties ()
{
Properties.SetString ("Icon.Name", "source-playlist");
Properties.SetString ("RemoveTracksActionLabel", Catalog.GetString ("Remove From Playlist"));
Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Delete Playlist"));
}
#region Source Overrides
public override bool AcceptsInputFromSource (Source source)
{
return base.AcceptsInputFromSource (source) && (
source == Parent || (source.Parent == Parent || Parent == null)
// This is commented out because we don't support (yet?) DnD from Play Queue to a playlist
//(source.Parent == Parent || Parent == null || (source.Parent == null && !(source is PrimarySource)))
);
}
public override SourceMergeType SupportedMergeTypes {
get { return SourceMergeType.All; }
}
#endregion
#region AbstractPlaylist overrides
protected override void AfterInitialized ()
{
base.AfterInitialized ();
if (PrimarySource != null) {
PrimarySource.TracksChanged += HandleTracksChanged;
PrimarySource.TracksDeleted += HandleTracksDeleted;
}
TrackModel.CanReorder = true;
}
protected override void Update ()
{
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (
String.Format (
@"UPDATE {0}
SET Name = ?,
SortColumn = ?,
SortType = ?,
CachedCount = ?,
IsTemporary = ?
WHERE PlaylistID = ?",
SourceTable
), Name, -1, 0, Count, IsTemporary, dbid
));
}
protected override void Create ()
{
DbId = ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (
@"INSERT INTO CorePlaylists (PlaylistID, Name, SortColumn, SortType, PrimarySourceID, IsTemporary)
VALUES (NULL, ?, ?, ?, ?, ?)",
Name, -1, 1, PrimarySourceId, IsTemporary //SortColumn, SortType
));
}
#endregion
#region DatabaseSource overrides
// We can add tracks only if our parent can
public override bool CanAddTracks {
get {
DatabaseSource ds = Parent as DatabaseSource;
return ds != null ? ds.CanAddTracks : base.CanAddTracks;
}
}
// We can remove tracks only if our parent can
public override bool CanRemoveTracks {
get {
return (Parent is PrimarySource)
? !(Parent as PrimarySource).PlaylistsReadOnly
: true;
}
}
#endregion
#region IUnmapableSource Implementation
public virtual bool Unmap ()
{
if (DbId != null) {
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
BEGIN TRANSACTION;
DELETE FROM CorePlaylists WHERE PlaylistID = ?;
DELETE FROM CorePlaylistEntries WHERE PlaylistID = ?;
COMMIT TRANSACTION",
DbId, DbId
));
}
ThreadAssist.ProxyToMain (Remove);
return true;
}
#endregion
protected void AddTrack (int track_id)
{
ServiceManager.DbConnection.Execute (add_track_command, DbId, track_id, MaxViewOrder);
OnTracksAdded ();
}
protected override void AddTrack (DatabaseTrackInfo track)
{
AddTrack (track.TrackId);
}
public override bool AddSelectedTracks (Source source, Selection selection)
{
if (Parent == null || source == Parent || source.Parent == Parent) {
return base.AddSelectedTracks (source, selection);
} else {
// Adding from a different primary source, so add to our primary source first
//PrimarySource primary = Parent as PrimarySource;
//primary.AddSelectedTracks (model);
// then add to us
//Log.Information ("Note: Feature Not Implemented", String.Format ("In this alpha release, you can only add tracks to {0} from {1} or its playlists.", Name, Parent.Name), true);
}
return false;
}
public virtual void ReorderSelectedTracks (int drop_row)
{
if (TrackModel.Selection.Count == 0 || TrackModel.Selection.AllSelected) {
return;
}
TrackInfo track = TrackModel[drop_row];
long order = track == null
? ServiceManager.DbConnection.Query<long> ("SELECT MAX(ViewOrder) + 1 FROM CorePlaylistEntries WHERE PlaylistID = ?", DbId)
: ServiceManager.DbConnection.Query<long> ("SELECT ViewOrder FROM CorePlaylistEntries WHERE PlaylistID = ? AND EntryID = ?", DbId, Convert.ToInt64 (track.CacheEntryId));
// Make room for our new items
if (track != null) {
ServiceManager.DbConnection.Execute ("UPDATE CorePlaylistEntries SET ViewOrder = ViewOrder + ? WHERE PlaylistID = ? AND ViewOrder >= ?",
TrackModel.Selection.Count, DbId, order
);
}
HyenaSqliteCommand update_command = new HyenaSqliteCommand (String.Format ("UPDATE CorePlaylistEntries SET ViewOrder = ? WHERE PlaylistID = {0} AND EntryID = ?", DbId));
HyenaSqliteCommand select_command = new HyenaSqliteCommand (String.Format ("SELECT ItemID FROM CoreCache WHERE ModelID = {0} LIMIT ?, ?", DatabaseTrackModel.CacheId));
// Reorder the selected items
ServiceManager.DbConnection.BeginTransaction ();
foreach (RangeCollection.Range range in TrackModel.Selection.Ranges) {
foreach (long entry_id in ServiceManager.DbConnection.QueryEnumerable<long> (select_command, range.Start, range.Count)) {
ServiceManager.DbConnection.Execute (update_command, order++, entry_id);
}
}
ServiceManager.DbConnection.CommitTransaction ();
Reload ();
}
DatabaseTrackListModel last_add_range_from_model;
HyenaSqliteCommand last_add_range_command = null;
protected override void AddTrackRange (DatabaseTrackListModel from, RangeCollection.Range range)
{
last_add_range_command = (!from.CachesJoinTableEntries)
? add_track_range_command
: from == last_add_range_from_model
? last_add_range_command
: new HyenaSqliteCommand (String.Format (add_track_range_from_joined_model_sql, from.JoinTable, from.JoinPrimaryKey));
long first_order_id = ServiceManager.DbConnection.Query<long> ("SELECT OrderID FROM CoreCache WHERE ModelID = ? LIMIT 1 OFFSET ?", from.CacheId, range.Start);
ServiceManager.DbConnection.Execute (last_add_range_command, DbId, MaxViewOrder - first_order_id, from.CacheId, range.Start, range.Count);
last_add_range_from_model = from;
}
protected override void RemoveTrackRange (DatabaseTrackListModel from, RangeCollection.Range range)
{
ServiceManager.DbConnection.Execute (remove_track_range_command,
DbId, from.CacheId, range.Start, range.Count);
}
protected override void HandleTracksChanged (Source sender, TrackEventArgs args)
{
if (args.When > last_updated) {
last_updated = args.When;
// Playlists do not need to reload if only certain columns are changed
if (NeedsReloadWhenFieldsChanged (args.ChangedFields)) {
// TODO Optimization: playlists only need to reload if one of their tracks was updated
//if (ServiceManager.DbConnection.Query<int> (count_updated_command, last_updated) > 0) {
Reload ();
//}
} else {
InvalidateCaches ();
}
}
}
protected override void HandleTracksDeleted (Source sender, TrackEventArgs args)
{
if (args.When > last_removed) {
last_removed = args.When;
Reload ();
/*if (ServiceManager.DbConnection.Query<int> (count_removed_command, last_removed) > 0) {
//ServiceManager.DbConnection.Execute ("DELETE FROM CoreCache WHERE ModelID = ? AND ItemID IN (SELECT EntryID FROM CorePlaylistEntries WHERE PlaylistID = ? AND TrackID IN (TrackID FROM CoreRemovedTracks))");
ServiceManager.DbConnection.Execute ("DELETE FROM CorePlaylistEntries WHERE TrackID IN (SELECT TrackID FROM CoreRemovedTracks)");
//track_model.UpdateAggregates ();
//OnUpdated ();
}*/
}
}
public static IEnumerable<PlaylistSource> LoadAll (PrimarySource parent)
{
ClearTemporary ();
using (HyenaDataReader reader = new HyenaDataReader (ServiceManager.DbConnection.Query (
@"SELECT PlaylistID, Name, SortColumn, SortType, PrimarySourceID, CachedCount, IsTemporary FROM CorePlaylists
WHERE Special = 0 AND PrimarySourceID = ?", parent.DbId))) {
while (reader.Read ()) {
yield return new PlaylistSource (
reader.Get<string> (1), reader.Get<int> (0),
reader.Get<int> (2), reader.Get<int> (3), parent,
reader.Get<int> (5), reader.Get<bool> (6)
);
}
}
}
private static void ClearTemporary ()
{
ServiceManager.DbConnection.BeginTransaction ();
ServiceManager.DbConnection.Execute (@"
DELETE FROM CorePlaylistEntries WHERE PlaylistID IN (SELECT PlaylistID FROM CorePlaylists WHERE IsTemporary = 1);
DELETE FROM CorePlaylists WHERE IsTemporary = 1;"
);
ServiceManager.DbConnection.CommitTransaction ();
}
private static int GetPlaylistId (string name)
{
return ServiceManager.DbConnection.Query<int> (
"SELECT PlaylistID FROM Playlists WHERE Name = ? LIMIT 1", name
);
}
private static bool PlaylistExists (string name)
{
return GetPlaylistId (name) > 0;
}
public static string CreateUniqueName ()
{
return NamingUtil.PostfixDuplicate (Catalog.GetString ("New Playlist"), PlaylistExists);
}
public static string CreateUniqueName (IEnumerable tracks)
{
return NamingUtil.PostfixDuplicate (NamingUtil.GenerateTrackCollectionName (
tracks, Catalog.GetString ("New Playlist")), PlaylistExists);
}
}
}
| |
// 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.Security;
namespace System.IO.MemoryMappedFiles
{
public partial class MemoryMappedFile
{
/// <summary>
/// Used by the 2 Create factory method groups. A null fileHandle specifies that the
/// memory mapped file should not be associated with an existing file on disk (ie start
/// out empty).
/// </summary>
[SecurityCritical]
private static unsafe SafeMemoryMappedFileHandle CreateCore(
FileStream fileStream, string mapName,
HandleInheritability inheritability, MemoryMappedFileAccess access,
MemoryMappedFileOptions options, long capacity)
{
if (mapName != null)
{
// Named maps are not supported in our Unix implementation. We could support named maps on Linux using
// shared memory segments (shmget/shmat/shmdt/shmctl/etc.), but that doesn't work on OSX by default due
// to very low default limits on OSX for the size of such objects; it also doesn't support behaviors
// like copy-on-write or the ability to control handle inheritability, and reliably cleaning them up
// relies on some non-conforming behaviors around shared memory IDs remaining valid even after they've
// been marked for deletion (IPC_RMID). We could also support named maps using the current implementation
// by not unlinking after creating the backing store, but then the backing stores would remain around
// and accessible even after process exit, with no good way to appropriately clean them up.
// (File-backed maps may still be used for cross-process communication.)
throw CreateNamedMapsNotSupportedException();
}
bool ownsFileStream = false;
if (fileStream != null)
{
// This map is backed by a file. Make sure the file's size is increased to be
// at least as big as the requested capacity of the map.
if (fileStream.Length < capacity)
{
try
{
fileStream.SetLength(capacity);
}
catch (ArgumentException exc)
{
// If the capacity is too large, we'll get an ArgumentException from SetLength,
// but on Windows this same condition is represented by an IOException.
throw new IOException(exc.Message, exc);
}
}
}
else
{
// This map is backed by memory-only. With files, multiple views over the same map
// will end up being able to share data through the same file-based backing store;
// for anonymous maps, we need a similar backing store, or else multiple views would logically
// each be their own map and wouldn't share any data. To achieve this, we create a backing object
// (either memory or on disk, depending on the system) and use its file descriptor as the file handle.
// However, we only do this when the permission is more than read-only. We can't change the size
// of an object that has read-only permissions, but we also don't need to worry about sharing
// views over a read-only, anonymous, memory-backed map, because the data will never change, so all views
// will always see zero and can't change that. In that case, we just use the built-in anonymous support of
// the map by leaving fileStream as null.
Interop.Sys.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false);
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0)
{
ownsFileStream = true;
fileStream = CreateSharedBackingObject(protections, capacity);
// If the MMF handle should not be inherited, mark the backing object fd as O_CLOEXEC.
if (inheritability == HandleInheritability.None)
{
Interop.CheckIo(Interop.Sys.Fcntl.SetCloseOnExec(fileStream.SafeFileHandle));
}
}
}
return new SafeMemoryMappedFileHandle(fileStream, ownsFileStream, inheritability, access, options, capacity);
}
/// <summary>
/// Used by the CreateOrOpen factory method groups.
/// </summary>
[SecurityCritical]
private static SafeMemoryMappedFileHandle CreateOrOpenCore(
string mapName,
HandleInheritability inheritability, MemoryMappedFileAccess access,
MemoryMappedFileOptions options, long capacity)
{
// Since we don't support mapName != null, CreateOrOpenCore can't
// be used to Open an existing map, and thus is identical to CreateCore.
return CreateCore(null, mapName, inheritability, access, options, capacity);
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
[SecurityCritical]
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, bool createOrOpen)
{
throw CreateNamedMapsNotSupportedException();
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
[SecurityCritical]
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen)
{
throw CreateNamedMapsNotSupportedException();
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Gets an exception indicating that named maps are not supported on this platform.</summary>
private static Exception CreateNamedMapsNotSupportedException()
{
return new PlatformNotSupportedException(SR.PlatformNotSupported_NamedMaps);
}
private static FileAccess TranslateProtectionsToFileAccess(Interop.Sys.MemoryMappedProtections protections)
{
return
(protections & (Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite :
(protections & (Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write :
FileAccess.Read;
}
private static FileStream CreateSharedBackingObject(Interop.Sys.MemoryMappedProtections protections, long capacity)
{
return CreateSharedBackingObjectUsingMemory(protections, capacity)
?? CreateSharedBackingObjectUsingFile(protections, capacity);
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private static FileStream CreateSharedBackingObjectUsingMemory(
Interop.Sys.MemoryMappedProtections protections, long capacity)
{
// The POSIX shared memory object name must begin with '/'. After that we just want something short and unique.
string mapName = "/corefx_map_" + Guid.NewGuid().ToString("N");
// Determine the flags to use when creating the shared memory object
Interop.Sys.OpenFlags flags = (protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 ?
Interop.Sys.OpenFlags.O_RDWR :
Interop.Sys.OpenFlags.O_RDONLY;
flags |= Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL; // CreateNew
// Determine the permissions with which to create the file
Interop.Sys.Permissions perms = default(Interop.Sys.Permissions);
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_READ) != 0)
perms |= Interop.Sys.Permissions.S_IRUSR;
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0)
perms |= Interop.Sys.Permissions.S_IWUSR;
if ((protections & Interop.Sys.MemoryMappedProtections.PROT_EXEC) != 0)
perms |= Interop.Sys.Permissions.S_IXUSR;
// Create the shared memory object.
SafeFileHandle fd = Interop.Sys.ShmOpen(mapName, flags, (int)perms);
if (fd.IsInvalid)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.ENOTSUP)
{
// If ShmOpen is not supported, fall back to file backing object.
// Note that the System.Native shim will force this failure on platforms where
// the result of native shm_open does not work well with our subsequent call
// to mmap.
return null;
}
throw Interop.GetExceptionForIoErrno(errorInfo);
}
try
{
// Unlink the shared memory object immediatley so that it'll go away once all handles
// to it are closed (as with opened then unlinked files, it'll remain usable via
// the open handles even though it's unlinked and can't be opened anew via its name).
Interop.CheckIo(Interop.Sys.ShmUnlink(mapName));
// Give it the right capacity. We do this directly with ftruncate rather
// than via FileStream.SetLength after the FileStream is created because, on some systems,
// lseek fails on shared memory objects, causing the FileStream to think it's unseekable,
// causing it to preemptively throw from SetLength.
Interop.CheckIo(Interop.Sys.FTruncate(fd, capacity));
// Wrap the file descriptor in a stream and return it.
return new FileStream(fd, TranslateProtectionsToFileAccess(protections));
}
catch
{
fd.Dispose();
throw;
}
}
private static string s_tempMapsDirectory;
private static FileStream CreateSharedBackingObjectUsingFile(Interop.Sys.MemoryMappedProtections protections, long capacity)
{
string tempMapsDirectory = s_tempMapsDirectory ?? (s_tempMapsDirectory = PersistedFiles.GetTempFeatureDirectory("maps"));
Directory.CreateDirectory(tempMapsDirectory);
string path = Path.Combine(tempMapsDirectory, Guid.NewGuid().ToString("N"));
FileAccess access =
(protections & (Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite :
(protections & (Interop.Sys.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write :
FileAccess.Read;
// Create the backing file, then immediately unlink it so that it'll be cleaned up when no longer in use.
// Then enlarge it to the requested capacity.
const int DefaultBufferSize = 0x1000;
var fs = new FileStream(path, FileMode.CreateNew, TranslateProtectionsToFileAccess(protections), FileShare.ReadWrite, DefaultBufferSize);
try
{
Interop.CheckIo(Interop.Sys.Unlink(path));
fs.SetLength(capacity);
}
catch
{
fs.Dispose();
throw;
}
return fs;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V10.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>PaymentsAccount</c> resource.</summary>
public sealed partial class PaymentsAccountName : gax::IResourceName, sys::IEquatable<PaymentsAccountName>
{
/// <summary>The possible contents of <see cref="PaymentsAccountName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/paymentsAccounts/{payments_account_id}</c>.
/// </summary>
CustomerPaymentsAccount = 1,
}
private static gax::PathTemplate s_customerPaymentsAccount = new gax::PathTemplate("customers/{customer_id}/paymentsAccounts/{payments_account_id}");
/// <summary>Creates a <see cref="PaymentsAccountName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="PaymentsAccountName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static PaymentsAccountName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new PaymentsAccountName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="PaymentsAccountName"/> with the pattern
/// <c>customers/{customer_id}/paymentsAccounts/{payments_account_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="paymentsAccountId">The <c>PaymentsAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="PaymentsAccountName"/> constructed from the provided ids.</returns>
public static PaymentsAccountName FromCustomerPaymentsAccount(string customerId, string paymentsAccountId) =>
new PaymentsAccountName(ResourceNameType.CustomerPaymentsAccount, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), paymentsAccountId: gax::GaxPreconditions.CheckNotNullOrEmpty(paymentsAccountId, nameof(paymentsAccountId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PaymentsAccountName"/> with pattern
/// <c>customers/{customer_id}/paymentsAccounts/{payments_account_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="paymentsAccountId">The <c>PaymentsAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PaymentsAccountName"/> with pattern
/// <c>customers/{customer_id}/paymentsAccounts/{payments_account_id}</c>.
/// </returns>
public static string Format(string customerId, string paymentsAccountId) =>
FormatCustomerPaymentsAccount(customerId, paymentsAccountId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PaymentsAccountName"/> with pattern
/// <c>customers/{customer_id}/paymentsAccounts/{payments_account_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="paymentsAccountId">The <c>PaymentsAccount</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PaymentsAccountName"/> with pattern
/// <c>customers/{customer_id}/paymentsAccounts/{payments_account_id}</c>.
/// </returns>
public static string FormatCustomerPaymentsAccount(string customerId, string paymentsAccountId) =>
s_customerPaymentsAccount.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(paymentsAccountId, nameof(paymentsAccountId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="PaymentsAccountName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/paymentsAccounts/{payments_account_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="paymentsAccountName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="PaymentsAccountName"/> if successful.</returns>
public static PaymentsAccountName Parse(string paymentsAccountName) => Parse(paymentsAccountName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="PaymentsAccountName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/paymentsAccounts/{payments_account_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="paymentsAccountName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="PaymentsAccountName"/> if successful.</returns>
public static PaymentsAccountName Parse(string paymentsAccountName, bool allowUnparsed) =>
TryParse(paymentsAccountName, allowUnparsed, out PaymentsAccountName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PaymentsAccountName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/paymentsAccounts/{payments_account_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="paymentsAccountName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PaymentsAccountName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string paymentsAccountName, out PaymentsAccountName result) =>
TryParse(paymentsAccountName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PaymentsAccountName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/paymentsAccounts/{payments_account_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="paymentsAccountName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PaymentsAccountName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string paymentsAccountName, bool allowUnparsed, out PaymentsAccountName result)
{
gax::GaxPreconditions.CheckNotNull(paymentsAccountName, nameof(paymentsAccountName));
gax::TemplatedResourceName resourceName;
if (s_customerPaymentsAccount.TryParseName(paymentsAccountName, out resourceName))
{
result = FromCustomerPaymentsAccount(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(paymentsAccountName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private PaymentsAccountName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string paymentsAccountId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
PaymentsAccountId = paymentsAccountId;
}
/// <summary>
/// Constructs a new instance of a <see cref="PaymentsAccountName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/paymentsAccounts/{payments_account_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="paymentsAccountId">The <c>PaymentsAccount</c> ID. Must not be <c>null</c> or empty.</param>
public PaymentsAccountName(string customerId, string paymentsAccountId) : this(ResourceNameType.CustomerPaymentsAccount, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), paymentsAccountId: gax::GaxPreconditions.CheckNotNullOrEmpty(paymentsAccountId, nameof(paymentsAccountId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>PaymentsAccount</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string PaymentsAccountId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerPaymentsAccount: return s_customerPaymentsAccount.Expand(CustomerId, PaymentsAccountId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as PaymentsAccountName);
/// <inheritdoc/>
public bool Equals(PaymentsAccountName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(PaymentsAccountName a, PaymentsAccountName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(PaymentsAccountName a, PaymentsAccountName b) => !(a == b);
}
public partial class PaymentsAccount
{
/// <summary>
/// <see cref="gagvr::PaymentsAccountName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal PaymentsAccountName ResourceNameAsPaymentsAccountName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::PaymentsAccountName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::PaymentsAccountName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal PaymentsAccountName PaymentsAccountName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::PaymentsAccountName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CustomerName"/>-typed view over the <see cref="PayingManagerCustomer"/> resource name property.
/// </summary>
internal CustomerName PayingManagerCustomerAsCustomerName
{
get => string.IsNullOrEmpty(PayingManagerCustomer) ? null : CustomerName.Parse(PayingManagerCustomer, allowUnparsed: true);
set => PayingManagerCustomer = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
namespace System
{
/// <summary>
/// Extension methods for Span{T}, Memory{T}, and friends.
/// </summary>
public static partial class MemoryExtensions
{
/// <summary>
/// Returns a value indicating whether the specified <paramref name="value"/> occurs within the <paramref name="span"/>.
/// <param name="span">The source span.</param>
/// <param name="value">The value to seek within the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
/// </summary>
public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
{
return (IndexOf(span, value, comparisonType) >= 0);
}
/// <summary>
/// Determines whether this <paramref name="span"/> and the specified <paramref name="other"/> span have the same characters
/// when compared using the specified <paramref name="comparisonType"/> option.
/// <param name="span">The source span.</param>
/// <param name="other">The value to compare with the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="other"/> are compared.</param>
/// </summary>
public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (CultureInfo.CurrentCulture.CompareInfo.CompareOptionNone(span, other) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.CompareOptionIgnoreCase(span, other) == 0);
case StringComparison.InvariantCulture:
return (CompareInfo.Invariant.CompareOptionNone(span, other) == 0);
case StringComparison.InvariantCultureIgnoreCase:
return (CompareInfo.Invariant.CompareOptionIgnoreCase(span, other) == 0);
case StringComparison.Ordinal:
return EqualsOrdinal(span, other);
case StringComparison.OrdinalIgnoreCase:
return EqualsOrdinalIgnoreCase(span, other);
}
Debug.Fail("StringComparison outside range");
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool EqualsOrdinal(this ReadOnlySpan<char> span, ReadOnlySpan<char> value)
{
if (span.Length != value.Length)
return false;
if (value.Length == 0) // span.Length == value.Length == 0
return true;
return span.SequenceEqual(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool EqualsOrdinalIgnoreCase(this ReadOnlySpan<char> span, ReadOnlySpan<char> value)
{
if (span.Length != value.Length)
return false;
if (value.Length == 0) // span.Length == value.Length == 0
return true;
return CompareInfo.EqualsOrdinalIgnoreCase(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), span.Length);
}
/// <summary>
/// Compares the specified <paramref name="span"/> and <paramref name="other"/> using the specified <paramref name="comparisonType"/>,
/// and returns an integer that indicates their relative position in the sort order.
/// <param name="span">The source span.</param>
/// <param name="other">The value to compare with the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="other"/> are compared.</param>
/// </summary>
public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.CompareOptionNone(span, other);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.CompareOptionIgnoreCase(span, other);
case StringComparison.InvariantCulture:
return CompareInfo.Invariant.CompareOptionNone(span, other);
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.CompareOptionIgnoreCase(span, other);
case StringComparison.Ordinal:
if (span.Length == 0 || other.Length == 0)
return span.Length - other.Length;
return string.CompareOrdinal(span, other);
case StringComparison.OrdinalIgnoreCase:
return CompareInfo.CompareOrdinalIgnoreCase(span, other);
}
Debug.Fail("StringComparison outside range");
return 0;
}
/// <summary>
/// Reports the zero-based index of the first occurrence of the specified <paramref name="value"/> in the current <paramref name="span"/>.
/// <param name="span">The source span.</param>
/// <param name="value">The value to seek within the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
/// </summary>
public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
if (value.Length == 0)
{
return 0;
}
if (span.Length == 0)
{
return -1;
}
if (comparisonType == StringComparison.Ordinal)
{
return SpanHelpers.IndexOf(
ref MemoryMarshal.GetReference(span),
span.Length,
ref MemoryMarshal.GetReference(value),
value.Length);
}
if (GlobalizationMode.Invariant)
{
return CompareInfo.InvariantIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None);
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
default:
Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase);
return CompareInfo.Invariant.IndexOfOrdinalIgnoreCase(span, value);
}
}
/// <summary>
/// Reports the zero-based index of the last occurrence of the specified <paramref name="value"/> in the current <paramref name="span"/>.
/// <param name="span">The source span.</param>
/// <param name="value">The value to seek within the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
/// </summary>
public static int LastIndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
if (value.Length == 0)
{
return span.Length > 0 ? span.Length - 1 : 0;
}
if (span.Length == 0)
{
return -1;
}
if (GlobalizationMode.Invariant)
{
return CompareInfo.InvariantIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None, fromBeginning: false);
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
default:
Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase);
return CompareInfo.Invariant.LastIndexOfOrdinal(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None);
}
}
/// <summary>
/// Copies the characters from the source span into the destination, converting each character to lowercase,
/// using the casing rules of the specified culture.
/// </summary>
/// <param name="source">The source span.</param>
/// <param name="destination">The destination span which contains the transformed characters.</param>
/// <param name="culture">An object that supplies culture-specific casing rules.</param>
/// <remarks>If the source and destinations overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.</remarks>
/// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
/// <exception cref="System.ArgumentNullException">
/// Thrown when <paramref name="culture"/> is null.
/// </exception>
public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture)
{
if (culture == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture);
// Assuming that changing case does not affect length
if (destination.Length < source.Length)
return -1;
if (GlobalizationMode.Invariant)
TextInfo.ToLowerAsciiInvariant(source, destination);
else
culture.TextInfo.ChangeCaseToLower(source, destination);
return source.Length;
}
/// <summary>
/// Copies the characters from the source span into the destination, converting each character to lowercase,
/// using the casing rules of the invariant culture.
/// </summary>
/// <param name="source">The source span.</param>
/// <param name="destination">The destination span which contains the transformed characters.</param>
/// <remarks>If the source and destinations overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.</remarks>
/// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination)
{
// Assuming that changing case does not affect length
if (destination.Length < source.Length)
return -1;
if (GlobalizationMode.Invariant)
TextInfo.ToLowerAsciiInvariant(source, destination);
else
CultureInfo.InvariantCulture.TextInfo.ChangeCaseToLower(source, destination);
return source.Length;
}
/// <summary>
/// Copies the characters from the source span into the destination, converting each character to uppercase,
/// using the casing rules of the specified culture.
/// </summary>
/// <param name="source">The source span.</param>
/// <param name="destination">The destination span which contains the transformed characters.</param>
/// <param name="culture">An object that supplies culture-specific casing rules.</param>
/// <remarks>If the source and destinations overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.</remarks>
/// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
/// <exception cref="System.ArgumentNullException">
/// Thrown when <paramref name="culture"/> is null.
/// </exception>
public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture)
{
if (culture == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture);
// Assuming that changing case does not affect length
if (destination.Length < source.Length)
return -1;
if (GlobalizationMode.Invariant)
TextInfo.ToUpperAsciiInvariant(source, destination);
else
culture.TextInfo.ChangeCaseToUpper(source, destination);
return source.Length;
}
/// <summary>
/// Copies the characters from the source span into the destination, converting each character to uppercase
/// using the casing rules of the invariant culture.
/// </summary>
/// <param name="source">The source span.</param>
/// <param name="destination">The destination span which contains the transformed characters.</param>
/// <remarks>If the source and destinations overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.</remarks>
/// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination)
{
// Assuming that changing case does not affect length
if (destination.Length < source.Length)
return -1;
if (GlobalizationMode.Invariant)
TextInfo.ToUpperAsciiInvariant(source, destination);
else
CultureInfo.InvariantCulture.TextInfo.ChangeCaseToUpper(source, destination);
return source.Length;
}
/// <summary>
/// Determines whether the end of the <paramref name="span"/> matches the specified <paramref name="value"/> when compared using the specified <paramref name="comparisonType"/> option.
/// </summary>
/// <param name="span">The source span.</param>
/// <param name="value">The sequence to compare to the end of the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
if (value.Length == 0)
{
return true;
}
if (comparisonType >= StringComparison.Ordinal || GlobalizationMode.Invariant)
{
if (string.GetCaseCompareOfComparisonCulture(comparisonType) == CompareOptions.None)
return span.EndsWith(value);
return (span.Length >= value.Length) ? (CompareInfo.CompareOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value) == 0) : false;
}
if (span.Length == 0)
{
return false;
}
return (comparisonType >= StringComparison.InvariantCulture) ?
CompareInfo.Invariant.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)) :
CultureInfo.CurrentCulture.CompareInfo.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
}
/// <summary>
/// Determines whether the beginning of the <paramref name="span"/> matches the specified <paramref name="value"/> when compared using the specified <paramref name="comparisonType"/> option.
/// </summary>
/// <param name="span">The source span.</param>
/// <param name="value">The sequence to compare to the beginning of the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
if (value.Length == 0)
{
return true;
}
if (comparisonType >= StringComparison.Ordinal || GlobalizationMode.Invariant)
{
if (string.GetCaseCompareOfComparisonCulture(comparisonType) == CompareOptions.None)
return span.StartsWith(value);
return (span.Length >= value.Length) ? (CompareInfo.CompareOrdinalIgnoreCase(span.Slice(0, value.Length), value) == 0) : false;
}
if (span.Length == 0)
{
return false;
}
return (comparisonType >= StringComparison.InvariantCulture) ?
CompareInfo.Invariant.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)) :
CultureInfo.CurrentCulture.CompareInfo.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
}
/// <summary>
/// Creates a new span over the portion of the target array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> AsSpan<T>(this T[] array, int start)
{
if (array == null)
{
if (start != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
return default;
}
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new Span<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start), array.Length - start);
}
/// <summary>
/// Creates a new span over the portion of the target array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> AsSpan<T>(this T[] array, Index startIndex)
{
if (array == null)
{
if (!startIndex.Equals(Index.Start))
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
return default;
}
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
int actualIndex = startIndex.GetOffset(array.Length);
if ((uint)actualIndex > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new Span<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), actualIndex), array.Length - actualIndex);
}
/// <summary>
/// Creates a new span over the portion of the target array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> AsSpan<T>(this T[] array, Range range)
{
if (array == null)
{
Index startIndex = range.Start;
Index endIndex = range.End;
if (!startIndex.Equals(Index.Start) || !endIndex.Equals(Index.Start))
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
return default;
}
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
(int start, int length) = range.GetOffsetAndLength(array.Length);
return new Span<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start), length);
}
/// <summary>
/// Creates a new readonly span over the portion of the target string.
/// </summary>
/// <param name="text">The target string.</param>
/// <remarks>Returns default when <paramref name="text"/> is null.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> AsSpan(this string text)
{
if (text == null)
return default;
return new ReadOnlySpan<char>(ref text.GetRawStringData(), text.Length);
}
/// <summary>
/// Creates a new readonly span over the portion of the target string.
/// </summary>
/// <param name="text">The target string.</param>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> AsSpan(this string text, int start)
{
if (text == null)
{
if (start != 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return default;
}
if ((uint)start > (uint)text.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetRawStringData(), start), text.Length - start);
}
/// <summary>
/// Creates a new readonly span over the portion of the target string.
/// </summary>
/// <param name="text">The target string.</param>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <remarks>Returns default when <paramref name="text"/> is null.</remarks>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> AsSpan(this string text, int start, int length)
{
if (text == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return default;
}
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)text.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
#else
if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
#endif
return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetRawStringData(), start), length);
}
/// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary>
/// <param name="text">The target string.</param>
/// <remarks>Returns default when <paramref name="text"/> is null.</remarks>
public static ReadOnlyMemory<char> AsMemory(this string text)
{
if (text == null)
return default;
return new ReadOnlyMemory<char>(text, 0, text.Length);
}
/// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary>
/// <param name="text">The target string.</param>
/// <param name="start">The index at which to begin this slice.</param>
/// <remarks>Returns default when <paramref name="text"/> is null.</remarks>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length).
/// </exception>
public static ReadOnlyMemory<char> AsMemory(this string text, int start)
{
if (text == null)
{
if (start != 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return default;
}
if ((uint)start > (uint)text.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return new ReadOnlyMemory<char>(text, start, text.Length - start);
}
/// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary>
/// <param name="text">The target string.</param>
/// <param name="startIndex">The index at which to begin this slice.</param>
public static ReadOnlyMemory<char> AsMemory(this string text, Index startIndex)
{
if (text == null)
{
if (!startIndex.Equals(Index.Start))
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
return default;
}
int actualIndex = startIndex.GetOffset(text.Length);
if ((uint)actualIndex > (uint)text.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new ReadOnlyMemory<char>(text, actualIndex, text.Length - actualIndex);
}
/// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary>
/// <param name="text">The target string.</param>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <remarks>Returns default when <paramref name="text"/> is null.</remarks>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range.
/// </exception>
public static ReadOnlyMemory<char> AsMemory(this string text, int start, int length)
{
if (text == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
return default;
}
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)text.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
#else
if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
#endif
return new ReadOnlyMemory<char>(text, start, length);
}
/// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary>
/// <param name="text">The target string.</param>
/// <param name="range">The range used to indicate the start and length of the sliced string.</param>
public static ReadOnlyMemory<char> AsMemory(this string text, Range range)
{
if (text == null)
{
Index startIndex = range.Start;
Index endIndex = range.End;
if (!startIndex.Equals(Index.Start) || !endIndex.Equals(Index.Start))
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
return default;
}
(int start, int length) = range.GetOffsetAndLength(text.Length);
return new ReadOnlyMemory<char>(text, start, length);
}
}
}
| |
#if NET462 && OLD
// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT!
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace OpenApiLib {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class ModelMessages {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_ProtoLongRange__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::OpenApiLib.ProtoLongRange, global::OpenApiLib.ProtoLongRange.Builder> internal__static_ProtoLongRange__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_ProtoDoubleRange__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::OpenApiLib.ProtoDoubleRange, global::OpenApiLib.ProtoDoubleRange.Builder> internal__static_ProtoDoubleRange__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static ModelMessages() {
byte[] descriptorData = global::System.Convert.FromBase64String(
"ChNNb2RlbE1lc3NhZ2VzLnByb3RvIioKDlByb3RvTG9uZ1JhbmdlEgwKBGZy" +
"b20YASABKAMSCgoCdG8YAiABKAMiLAoQUHJvdG9Eb3VibGVSYW5nZRIMCgRm" +
"cm9tGAEgASgBEgoKAnRvGAIgASgBKmUKEFByb3RvUGF5bG9hZFR5cGUSEQoN" +
"UFJPVE9fTUVTU0FHRRAFEg0KCUVSUk9SX1JFUxAyEhMKD0hFQVJUQkVBVF9F" +
"VkVOVBAzEgwKCFBJTkdfUkVREDQSDAoIUElOR19SRVMQNSrqAQoOUHJvdG9F" +
"cnJvckNvZGUSEQoNVU5LTk9XTl9FUlJPUhABEhcKE1VOU1VQUE9SVEVEX01F" +
"U1NBR0UQAhITCg9JTlZBTElEX1JFUVVFU1QQAxISCg5XUk9OR19QQVNTV09S" +
"RBAEEhEKDVRJTUVPVVRfRVJST1IQBRIUChBFTlRJVFlfTk9UX0ZPVU5EEAYS" +
"FgoSQ0FOVF9ST1VURV9SRVFVRVNUEAcSEgoORlJBTUVfVE9PX0xPTkcQCBIR" +
"Cg1NQVJLRVRfQ0xPU0VEEAkSGwoXQ09OQ1VSUkVOVF9NT0RJRklDQVRJT04Q" +
"CkJHCihjb20ueHRyYWRlci5wcm90b2NvbC5wcm90by5jb21tb25zLm1vZGVs" +
"QhZDb250YWluZXJNb2RlbE1lc3NhZ2VzUAGgAQE=");
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_ProtoLongRange__Descriptor = Descriptor.MessageTypes[0];
internal__static_ProtoLongRange__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::OpenApiLib.ProtoLongRange, global::OpenApiLib.ProtoLongRange.Builder>(internal__static_ProtoLongRange__Descriptor,
new string[] { "From", "To", });
internal__static_ProtoDoubleRange__Descriptor = Descriptor.MessageTypes[1];
internal__static_ProtoDoubleRange__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::OpenApiLib.ProtoDoubleRange, global::OpenApiLib.ProtoDoubleRange.Builder>(internal__static_ProtoDoubleRange__Descriptor,
new string[] { "From", "To", });
return null;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
#region Enums
public enum ProtoPayloadType {
PROTO_MESSAGE = 5,
ERROR_RES = 50,
HEARTBEAT_EVENT = 51,
PING_REQ = 52,
PING_RES = 53,
}
public enum ProtoErrorCode {
UNKNOWN_ERROR = 1,
UNSUPPORTED_MESSAGE = 2,
INVALID_REQUEST = 3,
WRONG_PASSWORD = 4,
TIMEOUT_ERROR = 5,
ENTITY_NOT_FOUND = 6,
CANT_ROUTE_REQUEST = 7,
FRAME_TOO_LONG = 8,
MARKET_CLOSED = 9,
CONCURRENT_MODIFICATION = 10,
}
#endregion
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ProtoLongRange : pb::GeneratedMessage<ProtoLongRange, ProtoLongRange.Builder> {
private ProtoLongRange() { }
private static readonly ProtoLongRange defaultInstance = new ProtoLongRange().MakeReadOnly();
private static readonly string[] _protoLongRangeFieldNames = new string[] { "from", "to" };
private static readonly uint[] _protoLongRangeFieldTags = new uint[] { 8, 16 };
public static ProtoLongRange DefaultInstance {
get { return defaultInstance; }
}
public override ProtoLongRange DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override ProtoLongRange ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::OpenApiLib.ModelMessages.internal__static_ProtoLongRange__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ProtoLongRange, ProtoLongRange.Builder> InternalFieldAccessors {
get { return global::OpenApiLib.ModelMessages.internal__static_ProtoLongRange__FieldAccessorTable; }
}
public const int FromFieldNumber = 1;
private bool hasFrom;
private long from_;
public bool HasFrom {
get { return hasFrom; }
}
public long From {
get { return from_; }
}
public const int ToFieldNumber = 2;
private bool hasTo;
private long to_;
public bool HasTo {
get { return hasTo; }
}
public long To {
get { return to_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
int size = SerializedSize;
string[] field_names = _protoLongRangeFieldNames;
if (hasFrom) {
output.WriteInt64(1, field_names[0], From);
}
if (hasTo) {
output.WriteInt64(2, field_names[1], To);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasFrom) {
size += pb::CodedOutputStream.ComputeInt64Size(1, From);
}
if (hasTo) {
size += pb::CodedOutputStream.ComputeInt64Size(2, To);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static ProtoLongRange ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ProtoLongRange ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ProtoLongRange ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ProtoLongRange ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ProtoLongRange ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ProtoLongRange ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static ProtoLongRange ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static ProtoLongRange ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static ProtoLongRange ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ProtoLongRange ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private ProtoLongRange MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(ProtoLongRange prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<ProtoLongRange, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(ProtoLongRange cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private ProtoLongRange result;
private ProtoLongRange PrepareBuilder() {
if (resultIsReadOnly) {
ProtoLongRange original = result;
result = new ProtoLongRange();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override ProtoLongRange MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::OpenApiLib.ProtoLongRange.Descriptor; }
}
public override ProtoLongRange DefaultInstanceForType {
get { return global::OpenApiLib.ProtoLongRange.DefaultInstance; }
}
public override ProtoLongRange BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is ProtoLongRange) {
return MergeFrom((ProtoLongRange) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(ProtoLongRange other) {
if (other == global::OpenApiLib.ProtoLongRange.DefaultInstance) return this;
PrepareBuilder();
if (other.HasFrom) {
From = other.From;
}
if (other.HasTo) {
To = other.To;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_protoLongRangeFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _protoLongRangeFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasFrom = input.ReadInt64(ref result.from_);
break;
}
case 16: {
result.hasTo = input.ReadInt64(ref result.to_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasFrom {
get { return result.hasFrom; }
}
public long From {
get { return result.From; }
set { SetFrom(value); }
}
public Builder SetFrom(long value) {
PrepareBuilder();
result.hasFrom = true;
result.from_ = value;
return this;
}
public Builder ClearFrom() {
PrepareBuilder();
result.hasFrom = false;
result.from_ = 0L;
return this;
}
public bool HasTo {
get { return result.hasTo; }
}
public long To {
get { return result.To; }
set { SetTo(value); }
}
public Builder SetTo(long value) {
PrepareBuilder();
result.hasTo = true;
result.to_ = value;
return this;
}
public Builder ClearTo() {
PrepareBuilder();
result.hasTo = false;
result.to_ = 0L;
return this;
}
}
static ProtoLongRange() {
object.ReferenceEquals(global::OpenApiLib.ModelMessages.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ProtoDoubleRange : pb::GeneratedMessage<ProtoDoubleRange, ProtoDoubleRange.Builder> {
private ProtoDoubleRange() { }
private static readonly ProtoDoubleRange defaultInstance = new ProtoDoubleRange().MakeReadOnly();
private static readonly string[] _protoDoubleRangeFieldNames = new string[] { "from", "to" };
private static readonly uint[] _protoDoubleRangeFieldTags = new uint[] { 9, 17 };
public static ProtoDoubleRange DefaultInstance {
get { return defaultInstance; }
}
public override ProtoDoubleRange DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override ProtoDoubleRange ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::OpenApiLib.ModelMessages.internal__static_ProtoDoubleRange__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ProtoDoubleRange, ProtoDoubleRange.Builder> InternalFieldAccessors {
get { return global::OpenApiLib.ModelMessages.internal__static_ProtoDoubleRange__FieldAccessorTable; }
}
public const int FromFieldNumber = 1;
private bool hasFrom;
private double from_;
public bool HasFrom {
get { return hasFrom; }
}
public double From {
get { return from_; }
}
public const int ToFieldNumber = 2;
private bool hasTo;
private double to_;
public bool HasTo {
get { return hasTo; }
}
public double To {
get { return to_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
int size = SerializedSize;
string[] field_names = _protoDoubleRangeFieldNames;
if (hasFrom) {
output.WriteDouble(1, field_names[0], From);
}
if (hasTo) {
output.WriteDouble(2, field_names[1], To);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasFrom) {
size += pb::CodedOutputStream.ComputeDoubleSize(1, From);
}
if (hasTo) {
size += pb::CodedOutputStream.ComputeDoubleSize(2, To);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static ProtoDoubleRange ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ProtoDoubleRange ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ProtoDoubleRange ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ProtoDoubleRange ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ProtoDoubleRange ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ProtoDoubleRange ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static ProtoDoubleRange ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static ProtoDoubleRange ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static ProtoDoubleRange ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ProtoDoubleRange ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private ProtoDoubleRange MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(ProtoDoubleRange prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<ProtoDoubleRange, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(ProtoDoubleRange cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private ProtoDoubleRange result;
private ProtoDoubleRange PrepareBuilder() {
if (resultIsReadOnly) {
ProtoDoubleRange original = result;
result = new ProtoDoubleRange();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override ProtoDoubleRange MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::OpenApiLib.ProtoDoubleRange.Descriptor; }
}
public override ProtoDoubleRange DefaultInstanceForType {
get { return global::OpenApiLib.ProtoDoubleRange.DefaultInstance; }
}
public override ProtoDoubleRange BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is ProtoDoubleRange) {
return MergeFrom((ProtoDoubleRange) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(ProtoDoubleRange other) {
if (other == global::OpenApiLib.ProtoDoubleRange.DefaultInstance) return this;
PrepareBuilder();
if (other.HasFrom) {
From = other.From;
}
if (other.HasTo) {
To = other.To;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_protoDoubleRangeFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _protoDoubleRangeFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 9: {
result.hasFrom = input.ReadDouble(ref result.from_);
break;
}
case 17: {
result.hasTo = input.ReadDouble(ref result.to_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasFrom {
get { return result.hasFrom; }
}
public double From {
get { return result.From; }
set { SetFrom(value); }
}
public Builder SetFrom(double value) {
PrepareBuilder();
result.hasFrom = true;
result.from_ = value;
return this;
}
public Builder ClearFrom() {
PrepareBuilder();
result.hasFrom = false;
result.from_ = 0D;
return this;
}
public bool HasTo {
get { return result.hasTo; }
}
public double To {
get { return result.To; }
set { SetTo(value); }
}
public Builder SetTo(double value) {
PrepareBuilder();
result.hasTo = true;
result.to_ = value;
return this;
}
public Builder ClearTo() {
PrepareBuilder();
result.hasTo = false;
result.to_ = 0D;
return this;
}
}
static ProtoDoubleRange() {
object.ReferenceEquals(global::OpenApiLib.ModelMessages.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
#endif
| |
//Synchronous template
//-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 11.04.2016
// Autor Fabio.Gruber
//
// Import gerber and excellon file output from Cadence Allegro (tools defined as comments beginning with ; and much more information like tolerance and quantity).
// It checks for unit MM or MILS.
// To use the script configurate the leading and trailing digits at the script begin.
//-----------------------------------------------------------------------------------
// GUID newScript_635954556024364499
using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;
namespace PCBIScript
{
public class PScript : IPCBIScript
{
public PScript()
{
}
IPCBIWindow Parent;
bool stop = false;
public void Execute(IPCBIWindow parent)
{
//import excellon file output from Cadence Allegro (tools defined as comments)
//insert digits for reading inner values of drill file (most no information in drill files, you can have a look on your gerber files to identify it).
//If you load gerber and drill together there is a auto scaling implemented.
int LeadingDigits = 2;
int TrailingDigits = 4;
bool UseMils = true;
Parent = parent;
IFilter filter = new IFilter(parent);
if (!parent.JobIsLoaded)
{
filter.CreateAndLoadEmptyJob(Path.GetTempPath(), "GerberImport", "step");
}
stop = false;
bool TryAutoSize = false;
string DrillHeader = "Format : " + LeadingDigits + "." + TrailingDigits + " / Absolute / INCH / Trailing*" + Environment.NewLine;
DrillHeader += "Contents: Thru / Drill / Plated*" + Environment.NewLine;
// DrillHeader += "M48**" + Environment.NewLine;
DrillHeader += "FMAT,1*" + Environment.NewLine;
DrillHeader += "INCH,TZ*" + Environment.NewLine;
DrillHeader += "ICI,OFF*";
ILayer drillLayer =null;
System.Windows.Forms.OpenFileDialog of = new System.Windows.Forms.OpenFileDialog();
of.Multiselect = true;
if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
PCB_Investigator.PCBIWindows.PCBIWorkingDialog working = new PCB_Investigator.PCBIWindows.PCBIWorkingDialog();
working.CanCancel(true);
working.CancelPressed += working_CancelPressed;
working.SetStatusText("Parsing files...");
working.ShowWorkingDlgAsThread();
double counter = 1;
double stepOneFile = 100f / of.FileNames.Length;
foreach (string FileName in of.FileNames)
{
if (stop) break;
working.SetStatusPercent((int)counter);
FileStream gfs = new System.IO.FileStream(FileName, FileMode.Open);
StreamReader gsr = new System.IO.StreamReader(gfs, Encoding.UTF8);
string GerberFile = gsr.ReadToEnd();
gsr.Close();
gfs.Close();
string fullPath = Path.GetTempPath() + Path.GetFileName(FileName);
counter += stepOneFile;
if (File.Exists(fullPath))
{
try
{
File.Delete(fullPath);
System.Threading.Thread.Sleep(1000); //file delete takes some time...
}
catch
{ }
}
FileStream writeGerberFS = new System.IO.FileStream(fullPath, FileMode.OpenOrCreate);
StreamWriter GerberWriterSW = new StreamWriter(writeGerberFS, Encoding.UTF8);
if (GerberFile.StartsWith("G"))
{
GerberWriterSW.WriteLine(GerberFile);
GerberWriterSW.Flush();
GerberWriterSW.Close();
IPCBIWindow.LoadInformation loadInfo = new IPCBIWindow.LoadInformation();
Parent.LoadData(fullPath, out loadInfo);
}
else if (GerberFile.StartsWith(";")) //most files out of cadance start with ;
{
GerberWriterSW.WriteLine(DrillHeader);
foreach (string s in GerberFile.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
{
//z.B. Tooldef. bzw. commentarte
//z.B. ; Holesize 1. = 16.000000 Tolerance = +0.000000/-0.000000 PLATED MILS Quantity = 57
if (s.StartsWith(";")) //nur wenn keine tooldef dann check Holesize def
{
#region check for tool definition in comment
int indexHolesize = s.IndexOf("Holesize");
if (indexHolesize > 0)
{
bool containsMil = s.Contains("MILS");
bool containsMM = s.Contains("MM");
//check = nach holesize
StringBuilder digitsOfDiameter = new StringBuilder();
bool started = false;
for (int i = indexHolesize + 9; i < s.Length; i++)
{
#region get diameter of holesize
if (s[i] == '=')
{
if (started) break;
started = true;
}
else
if (started)
{
if (char.IsNumber(s[i]) || s[i] == '.')
{
digitsOfDiameter.Append(s[i]);
}
else if (s[i] == ' ' && digitsOfDiameter.Length == 0)
{ }
else //anderer Parameter gestartet...
break;
}
#endregion
}
if (digitsOfDiameter.Length > 0)
{
if (containsMM && !containsMil)
{
double diameterTool = ParseHeader(digitsOfDiameter.ToString(), true) / 1000;
GerberWriterSW.WriteLine(s.Substring(1, 3) + "C" + diameterTool.ToString().Replace(",", "."));
}
else
GerberWriterSW.WriteLine(s.Substring(1, 3) + "C" + digitsOfDiameter.ToString());
}
}
else GerberWriterSW.WriteLine(s);
#endregion
}
}
GerberWriterSW.WriteLine(GerberFile);
GerberWriterSW.Flush();
GerberWriterSW.Close();
IStep step = parent.GetCurrentStep();
working.DoClose();
MessageBox.Show("Parameter"+ Environment.NewLine+"Leading "+LeadingDigits+" Trailing "+TrailingDigits+ Environment.NewLine+"Unit "+(UseMils?"mils":"mm")+ Environment.NewLine ,"Drill Setup");
IMatrix matrix = parent.GetMatrix();
if (matrix != null) matrix.DelateLayer(System.IO.Path.GetFileName( fullPath), false);
string drillLayername = step.AddGerberLayer(fullPath, true, PCBI.ImportOptions.FormatTypes.Excellon1, LeadingDigits, TrailingDigits, UseMils , TryAutoSize );
drillLayer = step.GetLayer(drillLayername);
Dictionary<double, int> diameterShapeList = new Dictionary<double, int>();
}
}
working.DoClose();
}
parent.UpdateControlsAndResetView();
if(drillLayer!=null)
drillLayer.EnableLayer(true);
}
void working_CancelPressed()
{
stop = true;
}
private double ParseHeader(string s, bool inMM)
{
try
{
double num = double.Parse(s, System.Globalization.NumberStyles.Any );
if (inMM)
{
return IMath.MM2Mils(num)/1000;
}
return num;
}
catch
{
return 1;//default size
}
}
}
}
| |
#region License
/*
* EndPointManager.cs
*
* This code is derived from EndPointManager.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2020 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <liryna.stark@gmail.com>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
namespace WebSocketSharp.Net
{
internal sealed class EndPointManager
{
#region Private Fields
private static readonly Dictionary<IPEndPoint, EndPointListener> _endpoints;
#endregion
#region Static Constructor
static EndPointManager ()
{
_endpoints = new Dictionary<IPEndPoint, EndPointListener> ();
}
#endregion
#region Private Constructors
private EndPointManager ()
{
}
#endregion
#region Private Methods
private static void addPrefix (string uriPrefix, HttpListener listener)
{
var pref = new HttpListenerPrefix (uriPrefix, listener);
var addr = convertToIPAddress (pref.Host);
if (addr == null) {
var msg = "The URI prefix includes an invalid host.";
throw new HttpListenerException (87, msg);
}
if (!addr.IsLocal ()) {
var msg = "The URI prefix includes an invalid host.";
throw new HttpListenerException (87, msg);
}
int port;
if (!Int32.TryParse (pref.Port, out port)) {
var msg = "The URI prefix includes an invalid port.";
throw new HttpListenerException (87, msg);
}
if (!port.IsPortNumber ()) {
var msg = "The URI prefix includes an invalid port.";
throw new HttpListenerException (87, msg);
}
var path = pref.Path;
if (path.IndexOf ('%') != -1) {
var msg = "The URI prefix includes an invalid path.";
throw new HttpListenerException (87, msg);
}
if (path.IndexOf ("//", StringComparison.Ordinal) != -1) {
var msg = "The URI prefix includes an invalid path.";
throw new HttpListenerException (87, msg);
}
var endpoint = new IPEndPoint (addr, port);
EndPointListener lsnr;
if (_endpoints.TryGetValue (endpoint, out lsnr)) {
if (lsnr.IsSecure ^ pref.IsSecure) {
var msg = "The URI prefix includes an invalid scheme.";
throw new HttpListenerException (87, msg);
}
}
else {
lsnr = new EndPointListener (
endpoint,
pref.IsSecure,
listener.CertificateFolderPath,
listener.SslConfiguration,
listener.ReuseAddress
);
_endpoints.Add (endpoint, lsnr);
}
lsnr.AddPrefix (pref);
}
private static IPAddress convertToIPAddress (string hostname)
{
if (hostname == "*")
return IPAddress.Any;
if (hostname == "+")
return IPAddress.Any;
return hostname.ToIPAddress ();
}
private static void removePrefix (string uriPrefix, HttpListener listener)
{
var pref = new HttpListenerPrefix (uriPrefix, listener);
var addr = convertToIPAddress (pref.Host);
if (addr == null)
return;
if (!addr.IsLocal ())
return;
int port;
if (!Int32.TryParse (pref.Port, out port))
return;
if (!port.IsPortNumber ())
return;
var path = pref.Path;
if (path.IndexOf ('%') != -1)
return;
if (path.IndexOf ("//", StringComparison.Ordinal) != -1)
return;
var endpoint = new IPEndPoint (addr, port);
EndPointListener lsnr;
if (!_endpoints.TryGetValue (endpoint, out lsnr))
return;
if (lsnr.IsSecure ^ pref.IsSecure)
return;
lsnr.RemovePrefix (pref);
}
#endregion
#region Internal Methods
internal static bool RemoveEndPoint (IPEndPoint endpoint)
{
lock (((ICollection) _endpoints).SyncRoot)
return _endpoints.Remove (endpoint);
}
#endregion
#region Public Methods
public static void AddListener (HttpListener listener)
{
var added = new List<string> ();
lock (((ICollection) _endpoints).SyncRoot) {
try {
foreach (var pref in listener.Prefixes) {
addPrefix (pref, listener);
added.Add (pref);
}
}
catch {
foreach (var pref in added)
removePrefix (pref, listener);
throw;
}
}
}
public static void AddPrefix (string uriPrefix, HttpListener listener)
{
lock (((ICollection) _endpoints).SyncRoot)
addPrefix (uriPrefix, listener);
}
public static void RemoveListener (HttpListener listener)
{
lock (((ICollection) _endpoints).SyncRoot) {
foreach (var pref in listener.Prefixes)
removePrefix (pref, listener);
}
}
public static void RemovePrefix (string uriPrefix, HttpListener listener)
{
lock (((ICollection) _endpoints).SyncRoot)
removePrefix (uriPrefix, listener);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Data;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalInventoryServicesConnector")]
public class LocalInventoryServicesConnector : ISharedRegionModule, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Scene used by this module. This currently needs to be publicly settable for HGInventoryBroker.
/// </summary>
public Scene Scene { get; set; }
private IInventoryService m_InventoryService;
private IUserManagement m_UserManager;
private IUserManagement UserManager
{
get
{
if (m_UserManager == null)
{
m_UserManager = Scene.RequestModuleInterface<IUserManagement>();
}
return m_UserManager;
}
}
private bool m_Enabled = false;
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalInventoryServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryServices", "");
if (name == Name)
{
IConfig inventoryConfig = source.Configs["InventoryService"];
if (inventoryConfig == null)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: InventoryService missing from OpenSim.ini");
return;
}
string serviceDll = inventoryConfig.GetString("LocalServiceModule", String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: No LocalServiceModule named in section InventoryService");
return;
}
Object[] args = new Object[] { source };
m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Service dll = {0}", serviceDll);
m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(serviceDll, args);
if (m_InventoryService == null)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: Can't load inventory service");
throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
}
m_Enabled = true;
m_log.Info("[LOCAL INVENTORY SERVICES CONNECTOR]: Local inventory connector enabled");
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IInventoryService>(this);
if (Scene == null)
Scene = scene;
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
}
#region IInventoryService
public bool CreateUserInventory(UUID user)
{
return m_InventoryService.CreateUserInventory(user);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
{
return m_InventoryService.GetInventorySkeleton(userId);
}
public InventoryCollection GetUserInventory(UUID id)
{
return m_InventoryService.GetUserInventory(id);
}
public void GetUserInventory(UUID userID, InventoryReceiptCallback callback)
{
m_InventoryService.GetUserInventory(userID, callback);
}
public InventoryFolderBase GetRootFolder(UUID userID)
{
return m_InventoryService.GetRootFolder(userID);
}
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
return m_InventoryService.GetFolderForType(userID, type);
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
InventoryCollection invCol = m_InventoryService.GetFolderContent(userID, folderID);
if (UserManager != null)
{
// Protect ourselves against the caller subsequently modifying the items list
List<InventoryItemBase> items = new List<InventoryItemBase>(invCol.Items);
Util.FireAndForget(delegate
{
foreach (InventoryItemBase item in items)
UserManager.AddUser(item.CreatorIdAsUuid, item.CreatorData);
});
}
return invCol;
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
return m_InventoryService.GetFolderItems(userID, folderID);
}
/// <summary>
/// Add a new folder to the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully added</returns>
public bool AddFolder(InventoryFolderBase folder)
{
return m_InventoryService.AddFolder(folder);
}
/// <summary>
/// Update a folder in the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully updated</returns>
public bool UpdateFolder(InventoryFolderBase folder)
{
return m_InventoryService.UpdateFolder(folder);
}
/// <summary>
/// Move an inventory folder to a new location
/// </summary>
/// <param name="folder">A folder containing the details of the new location</param>
/// <returns>true if the folder was successfully moved</returns>
public bool MoveFolder(InventoryFolderBase folder)
{
return m_InventoryService.MoveFolder(folder);
}
public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
return m_InventoryService.DeleteFolders(ownerID, folderIDs);
}
/// <summary>
/// Purge an inventory folder of all its items and subfolders.
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully purged</returns>
public bool PurgeFolder(InventoryFolderBase folder)
{
return m_InventoryService.PurgeFolder(folder);
}
public bool AddItem(InventoryItemBase item)
{
// m_log.DebugFormat(
// "[LOCAL INVENTORY SERVICES CONNECTOR]: Adding inventory item {0} to user {1} folder {2}",
// item.Name, item.Owner, item.Folder);
return m_InventoryService.AddItem(item);
}
/// <summary>
/// Update an item in the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully updated</returns>
public bool UpdateItem(InventoryItemBase item)
{
return m_InventoryService.UpdateItem(item);
}
public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
return m_InventoryService.MoveItems(ownerID, items);
}
/// <summary>
/// Delete an item from the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns>
public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
return m_InventoryService.DeleteItems(ownerID, itemIDs);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
// m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Requesting inventory item {0}", item.ID);
// UUID requestedItemId = item.ID;
item = m_InventoryService.GetItem(item);
// if (null == item)
// m_log.ErrorFormat(
// "[LOCAL INVENTORY SERVICES CONNECTOR]: Could not find item with id {0}", requestedItemId);
return item;
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
return m_InventoryService.GetFolder(folder);
}
/// <summary>
/// Does the given user have an inventory structure?
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public bool HasInventoryForUser(UUID userID)
{
return m_InventoryService.HasInventoryForUser(userID);
}
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
return m_InventoryService.GetActiveGestures(userId);
}
public int GetAssetPermissions(UUID userID, UUID assetID)
{
return m_InventoryService.GetAssetPermissions(userID, assetID);
}
#endregion IInventoryService
}
}
| |
/*
Copyright (c) 2011, Matt Howlett
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Nhiredis
{
public partial class RedisClient
{
private const int REDIS_REPLY_STRING = 1;
private const int REDIS_REPLY_ARRAY = 2;
private const int REDIS_REPLY_INTEGER = 3;
private const int REDIS_REPLY_NIL = 4;
private const int REDIS_REPLY_STATUS = 5;
private const int REDIS_REPLY_ERROR = 6;
private static UTF8Encoding enc = new UTF8Encoding(false);
private static byte[] StringToUtf8(string s)
{
return enc.GetBytes(s);
}
public static RedisContext RedisConnectWithTimeout(string host, int port, TimeSpan timeout)
{
int seconds = (int)(timeout.TotalSeconds);
int milliseconds = (int)(timeout.TotalMilliseconds - seconds*1000);
byte[] ipBytes = StringToUtf8(host);
unsafe
{
fixed (byte* pIpBytes = ipBytes)
{
var result = new RedisContext { NativeContext = Interop.redisConnectWithTimeoutX(new IntPtr(pIpBytes), ipBytes.Length, port, seconds, milliseconds * 1000) };
if (result.NativeContext == IntPtr.Zero)
{
throw new NhiredisException("Unable to establish redis connection [" + host + ":" + port + "]");
}
return result;
}
}
}
public static T RedisCommand<T>(RedisContext context, params object[] arguments)
{
object result = RedisCommandImpl(context, arguments, typeof(T));
if (!(result is T))
{
if (result != null)
{
throw new NhiredisException(
"Expecting RedisCommand reply to have type: " + typeof (T) +
", but type was " + result.GetType());
}
}
return (T)result;
}
public static object RedisCommand(
RedisContext context,
params object[] arguments)
{
return RedisCommandImpl(context, arguments, null);
}
private static ArrayList flattenArgumentList(object[] arguments)
{
var args = new ArrayList();
for (int i = 0; i < arguments.Length; ++i)
{
if (arguments[i] is IDictionary)
{
foreach (DictionaryEntry v in (IDictionary)arguments[i])
{
args.Add(v.Key.ToString());
args.Add(v.Value.ToString());
}
}
else if (!(arguments[i] is byte[]) && !(arguments[i] is string) && arguments[i] is IEnumerable)
{
foreach (var v in (IEnumerable)arguments[i])
{
if (v is byte[])
{
args.Add(v);
}
else
{
args.Add(v.ToString());
}
}
}
else
{
if (arguments[i] is byte[])
{
args.Add(arguments[i]);
}
else
{
args.Add(arguments[i].ToString());
}
}
}
return args;
}
private static object handleArrayResult(Type typeHint, IntPtr replyObject, int elements)
{
int currentByteBufLength = 64;
var byteBuf = new byte[currentByteBufLength];
var result_o = (typeHint == null || typeHint == typeof(List<object>)) ? new List<object>() : null;
var result_s = (typeHint == typeof(List<string>) || typeof(IDictionary).IsAssignableFrom(typeHint)) ? new List<string>() : null;
var result_l = typeHint == typeof(List<long>) ? new List<long>() : null;
var result_i = typeHint == typeof(List<int>) ? new List<int>() : null;
var result_b = typeHint == typeof(List<byte[]>) ? new List<byte[]>() : null;
if (replyObject != IntPtr.Zero)
{
for (int i = 0; i < elements; ++i)
{
IntPtr strPtr;
int type;
long integer;
int len;
Interop.retrieveElementX(
replyObject,
i,
out type,
out integer,
byteBuf,
currentByteBufLength,
out len,
out strPtr);
if (strPtr != IntPtr.Zero)
{
currentByteBufLength = len;
byteBuf = new byte[len];
Interop.retrieveElementStringX(replyObject, i, byteBuf);
}
switch (type)
{
case REDIS_REPLY_STRING:
if (result_s != null)
{
result_s.Add(enc.GetString(byteBuf, 0, len));
}
else if (result_o != null)
{
result_o.Add(enc.GetString(byteBuf, 0, len));
}
else if (result_b != null)
{
var res = new byte[len];
for (int k = 0; k < len; ++k)
{
res[k] = byteBuf[k];
}
result_b.Add(res);
}
else if (result_l != null)
{
long result;
if (!long.TryParse(enc.GetString(byteBuf, 0, len), out result))
{
result = long.MinValue;
}
result_l.Add(result);
}
else if (result_i != null)
{
int result;
if (!int.TryParse(enc.GetString(byteBuf, 0, len), out result))
{
result = int.MinValue;
}
result_i.Add(result);
}
break;
case REDIS_REPLY_INTEGER:
if (result_l != null)
{
result_l.Add(integer);
}
else if (result_i != null)
{
result_i.Add((int)integer);
}
else if (result_o != null)
{
result_o.Add(integer);
}
else if (result_s != null)
{
result_s.Add(integer.ToString());
}
else if (result_b != null)
{
result_b.Add(BitConverter.GetBytes(integer));
}
break;
case REDIS_REPLY_ARRAY:
if (result_o != null)
{
result_o.Add(null);
}
else if (result_s != null)
{
result_s.Add(null);
}
else if (result_l != null)
{
result_l.Add(long.MinValue);
}
else if (result_i != null)
{
result_i.Add(int.MinValue);
}
else if (result_b != null)
{
result_b.Add(null);
}
break;
case REDIS_REPLY_NIL:
if (result_o != null)
{
result_o.Add(null);
}
else if (result_s != null)
{
result_s.Add(null);
}
else if (result_l != null)
{
result_l.Add(long.MinValue);
}
else if (result_i != null)
{
result_i.Add(int.MinValue);
}
else if (result_b != null)
{
result_b.Add(null);
}
break;
case REDIS_REPLY_STATUS:
if (result_s != null)
{
result_s.Add(enc.GetString(byteBuf, 0, len));
}
else if (result_o != null)
{
result_o.Add(enc.GetString(byteBuf, 0, len));
}
else if (result_l != null)
{
long result;
if (!long.TryParse(enc.GetString(byteBuf, 0, len), out result))
{
result = long.MinValue;
}
result_l.Add(result);
}
else if (result_i != null)
{
int result;
if (!int.TryParse(enc.GetString(byteBuf, 0, len), out result))
{
result = int.MinValue;
}
result_i.Add(result);
}
else if (result_b != null)
{
var res = new byte[len];
for (int k = 0; k < len; ++k)
{
res[k] = byteBuf[k];
}
result_b.Add(res);
}
break;
case REDIS_REPLY_ERROR:
if (result_s != null)
{
result_s.Add(enc.GetString(byteBuf, 0, len));
}
else if (result_o != null)
{
result_o.Add(enc.GetString(byteBuf, 0, len));
}
else if (result_l != null)
{
result_l.Add(long.MinValue);
}
else if (result_i != null)
{
result_i.Add(int.MinValue);
}
else if (result_b != null)
{
result_b.Add(null);
}
break;
default:
throw new NhiredisException("Unknown redis return type: " + type);
}
}
Interop.freeReplyObjectX(replyObject);
}
if (result_s != null)
{
if (typeof(IDictionary).IsAssignableFrom(typeHint))
{
return Utils.ConstructDictionary(result_s, typeHint);
}
return result_s;
}
if (result_o != null)
{
return result_o;
}
if (result_l != null)
{
return result_l;
}
if (result_i != null)
{
return result_i;
}
if (result_b != null)
{
return result_b;
}
return null;
}
private static object handleIntegerResult(Type typeHint, long integer)
{
if (typeHint == typeof(int) || typeHint == typeof(int?))
{
return (int) integer;
}
if (typeHint == typeof(string))
{
return integer.ToString();
}
if (typeHint == typeof (long) || typeHint == typeof(long?))
{
return (long) integer;
}
if (typeHint == typeof(double) || typeHint == typeof(double?))
{
return (double) integer;
}
if (typeHint == typeof(float) || typeHint == typeof(float?))
{
return (float) integer;
}
if (typeHint == typeof(bool) || typeHint == typeof(bool?))
{
if (integer == 1)
{
return true;
}
if (integer == 0)
{
return false;
}
return typeHint == typeof(bool?) ? null : new bool?(true);
}
if (typeHint == typeof(short) || typeHint == typeof(short?))
{
return (short) integer;
}
if (typeHint == typeof(byte) || typeHint == typeof(byte?))
{
return (byte) integer;
}
if (typeHint == typeof(UInt16) || typeHint == typeof(UInt16?))
{
return (UInt16) integer;
}
if (typeHint == typeof(UInt32) || typeHint == typeof(UInt32?))
{
return (UInt32) integer;
}
if (typeHint == typeof(UInt64) || typeHint == typeof(UInt64?))
{
return (UInt64) integer;
}
if (typeHint == typeof (Decimal) || typeHint == typeof (Decimal?))
{
return (Decimal) integer;
}
return integer;
}
private static object handleStringResult(Type typeHint, IntPtr replyObject, int resultLen)
{
var byteBuf = new byte[resultLen];
if (replyObject != IntPtr.Zero)
{
Interop.retrieveStringAndFreeReplyObjectX(replyObject, byteBuf);
}
if (resultLen == 0)
{
return null;
}
if (typeHint == typeof(int) || typeHint == typeof(int?))
{
return int.Parse(enc.GetString(byteBuf, 0, resultLen));
}
if (typeHint == typeof(long) || typeHint == typeof(long?))
{
return long.Parse(enc.GetString(byteBuf, 0, resultLen));
}
if (typeHint == typeof(float) || typeHint == typeof(float?))
{
return float.Parse(enc.GetString(byteBuf, 0, resultLen));
}
if (typeHint == typeof(double) || typeHint == typeof(double?))
{
return double.Parse(enc.GetString(byteBuf, 0, resultLen));
}
if (typeHint == typeof(bool) || typeHint == typeof(bool?))
{
string s = enc.GetString(byteBuf, 0, resultLen);
if (s == "1")
{
return true;
}
if (s == "0")
{
return false;
}
if (s.ToLower() == "true")
{
return true;
}
if (s.ToLower() == "false")
{
return false;
}
return null;
}
if (typeHint == typeof(byte[]))
{
byte[] bytes = new byte[resultLen];
for (var i = 0; i < resultLen; ++i)
{
bytes[i] = byteBuf[i];
}
return bytes;
}
if (typeHint == typeof(byte) || typeHint == typeof(byte?))
{
return byte.Parse(enc.GetString(byteBuf, 0, resultLen));
}
if (typeHint == typeof(short) || typeHint == typeof(short?))
{
return short.Parse(enc.GetString(byteBuf, 0, resultLen));
}
if (typeHint == typeof(UInt16) || typeHint == typeof(UInt16?))
{
return UInt16.Parse(enc.GetString(byteBuf, 0, resultLen));
}
if (typeHint == typeof(UInt32) || typeHint == typeof(UInt32?))
{
return UInt32.Parse(enc.GetString(byteBuf, 0, resultLen));
}
if (typeHint == typeof(UInt64) || typeHint == typeof(UInt64?))
{
return UInt64.Parse(enc.GetString(byteBuf, 0, resultLen));
}
if (typeHint == typeof(Decimal) || typeHint == typeof(Decimal?))
{
return Decimal.Parse(enc.GetString(byteBuf, 0, resultLen));
}
return enc.GetString(byteBuf, 0, resultLen);
}
private static object RedisCommandImpl(
RedisContext context,
object[] arguments,
Type typeHint)
{
int currentByteBufLength = 64;
int type;
long integer;
var byteBuf = new byte[currentByteBufLength];
int elements;
IntPtr replyObject;
int len;
var args = flattenArgumentList(arguments);
// STEP 1. Set specify arguments.
IntPtr argumentsPtr = IntPtr.Zero;
if (args.Count > 0)
{
Interop.setupArgumentArrayX(args.Count, out argumentsPtr);
for (int i = 0; i < args.Count; ++i)
{
if (args[i] is byte[])
{
Interop.setArgumentX(argumentsPtr, i, (byte[])args[i], ((byte[])args[i]).Length);
}
else
{
byte[] arg = StringToUtf8((string) args[i]);
Interop.setArgumentX(argumentsPtr, i, arg, arg.Length);
}
}
}
// STEP 2. Execute command.
Interop.redisCommandX(
context.NativeContext,
argumentsPtr,
args.Count,
out type,
out integer,
byteBuf,
currentByteBufLength,
out len,
out elements,
out replyObject);
// STEP 3. Handle result.
switch (type)
{
case REDIS_REPLY_STRING:
return handleStringResult(typeHint, replyObject, len);
case REDIS_REPLY_ARRAY:
return handleArrayResult(typeHint, replyObject, elements);
case REDIS_REPLY_INTEGER:
return handleIntegerResult(typeHint, integer);
case REDIS_REPLY_NIL:
return null;
case REDIS_REPLY_STATUS:
if (replyObject != IntPtr.Zero)
{
currentByteBufLength = len;
byteBuf = new byte[currentByteBufLength];
Interop.retrieveStringAndFreeReplyObjectX(replyObject, byteBuf);
}
if (typeHint == typeof(int) || typeHint == typeof(int?))
{
return int.Parse(enc.GetString(byteBuf, 0, len));
}
if (typeHint == typeof(long) || typeHint == typeof(long?))
{
return long.Parse(enc.GetString(byteBuf, 0, len));
}
if (typeHint == typeof(float) || typeHint == typeof(float?))
{
return float.Parse(enc.GetString(byteBuf, 0, len));
}
if (typeHint == typeof(double) || typeHint == typeof(double?))
{
return double.Parse(enc.GetString(byteBuf, 0, len));
}
return enc.GetString(byteBuf, 0, len);
case REDIS_REPLY_ERROR:
if (replyObject != IntPtr.Zero)
{
currentByteBufLength = len ;
byteBuf = new byte[currentByteBufLength];
Interop.retrieveStringAndFreeReplyObjectX(replyObject, byteBuf);
}
throw new NhiredisException(enc.GetString(byteBuf, 0, len));
default:
throw new NhiredisException("Unknown redis return type: " + type);
}
}
private RedisContext _context;
public RedisClient(string host, int port, TimeSpan timeout)
{
_context = RedisConnectWithTimeout(host, port, timeout);
}
public T RedisCommand<T>(params object[] arguments)
{
return RedisCommand<T>(_context, arguments);
}
public object RedisCommand(params object[] arguments)
{
return RedisCommand(_context, arguments);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Collections.Concurrent;
using NHotkey;
using NHotkey.Wpf;
using NLog;
using Wox.Core.Plugin;
using Wox.Core.Resource;
using Wox.Helper;
using Wox.Infrastructure;
using Wox.Infrastructure.Hotkey;
using Wox.Infrastructure.Logger;
using Wox.Infrastructure.Storage;
using Wox.Infrastructure.UserSettings;
using Wox.Plugin;
using Wox.Storage;
namespace Wox.ViewModel
{
public class MainViewModel : BaseModel, ISavable
{
#region Private Fields
private Query _lastQuery;
private string _queryTextBeforeLeaveResults;
private readonly WoxJsonStorage<History> _historyItemsStorage;
private readonly WoxJsonStorage<UserSelectedRecord> _userSelectedRecordStorage;
private readonly WoxJsonStorage<TopMostRecord> _topMostRecordStorage;
private readonly Settings _settings;
private readonly History _history;
private readonly UserSelectedRecord _userSelectedRecord;
private readonly TopMostRecord _topMostRecord;
private BlockingCollection<ResultsForUpdate> _resultsQueue;
private CancellationTokenSource _updateSource;
private bool _saved;
private readonly Internationalization _translator;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
#endregion
#region Constructor
public MainViewModel(bool useUI = true)
{
_saved = false;
_queryTextBeforeLeaveResults = "";
_queryText = "";
_lastQuery = new Query();
_settings = Settings.Instance;
_historyItemsStorage = new WoxJsonStorage<History>();
_userSelectedRecordStorage = new WoxJsonStorage<UserSelectedRecord>();
_topMostRecordStorage = new WoxJsonStorage<TopMostRecord>();
_history = _historyItemsStorage.Load();
_userSelectedRecord = _userSelectedRecordStorage.Load();
_topMostRecord = _topMostRecordStorage.Load();
ContextMenu = new ResultsViewModel(_settings);
Results = new ResultsViewModel(_settings);
History = new ResultsViewModel(_settings);
_selectedResults = Results;
if (useUI)
{
_translator = InternationalizationManager.Instance;
InitializeKeyCommands();
RegisterResultsUpdatedEvent();
SetHotkey(_settings.Hotkey, OnHotkey);
SetCustomPluginHotkey();
}
RegisterResultConsume();
}
private void RegisterResultConsume()
{
_resultsQueue = new BlockingCollection<ResultsForUpdate>();
Task.Run(() =>
{
while (true)
{
ResultsForUpdate first = _resultsQueue.Take();
List<ResultsForUpdate> updates = new List<ResultsForUpdate>() { first };
DateTime startTime = DateTime.Now;
int timeout = 50;
DateTime takeExpired = startTime.AddMilliseconds(timeout / 10);
ResultsForUpdate tempUpdate;
while (_resultsQueue.TryTake(out tempUpdate) && DateTime.Now < takeExpired)
{
updates.Add(tempUpdate);
}
UpdateResultView(updates);
DateTime currentTime = DateTime.Now;
Logger.WoxTrace($"start {startTime.Millisecond} end {currentTime.Millisecond}");
foreach (var update in updates)
{
Logger.WoxTrace($"update name:{update.Metadata.Name} count:{update.Results.Count} query:{update.Query} token:{update.Token.IsCancellationRequested}");
update.Countdown.Signal();
}
DateTime viewExpired = startTime.AddMilliseconds(timeout);
if (currentTime < viewExpired)
{
TimeSpan span = viewExpired - currentTime;
Logger.WoxTrace($"expired { viewExpired.Millisecond} span {span.TotalMilliseconds}");
Thread.Sleep(span);
}
}
}).ContinueWith(ErrorReporting.UnhandledExceptionHandleTask, TaskContinuationOptions.OnlyOnFaulted);
}
private void RegisterResultsUpdatedEvent()
{
foreach (var pair in PluginManager.GetPluginsForInterface<IResultUpdated>())
{
var plugin = (IResultUpdated)pair.Plugin;
plugin.ResultsUpdated += (s, e) =>
{
if (!_updateSource.IsCancellationRequested)
{
CancellationToken token = _updateSource.Token;
// todo async update don't need count down
// init with 1 since every ResultsForUpdate will be countdown.signal()
CountdownEvent countdown = new CountdownEvent(1);
Task.Run(() =>
{
if (token.IsCancellationRequested) { return; }
PluginManager.UpdatePluginMetadata(e.Results, pair.Metadata, e.Query);
_resultsQueue.Add(new ResultsForUpdate(e.Results, pair.Metadata, e.Query, token, countdown));
}, token);
}
};
}
}
private void InitializeKeyCommands()
{
EscCommand = new RelayCommand(_ =>
{
if (!SelectedIsFromQueryResults())
{
SelectedResults = Results;
}
else
{
MainWindowVisibility = Visibility.Collapsed;
}
});
SelectNextItemCommand = new RelayCommand(_ =>
{
SelectedResults.SelectNextResult();
});
SelectPrevItemCommand = new RelayCommand(_ =>
{
SelectedResults.SelectPrevResult();
});
SelectNextPageCommand = new RelayCommand(_ =>
{
SelectedResults.SelectNextPage();
});
SelectPrevPageCommand = new RelayCommand(_ =>
{
SelectedResults.SelectPrevPage();
});
SelectFirstResultCommand = new RelayCommand(_ => SelectedResults.SelectFirstResult());
StartHelpCommand = new RelayCommand(_ =>
{
Process.Start("http://doc.wox.one/");
});
RefreshCommand = new RelayCommand(_ => Refresh());
OpenResultCommand = new RelayCommand(index =>
{
var results = SelectedResults;
if (index != null)
{
results.SelectedIndex = int.Parse(index.ToString());
}
var result = results.SelectedItem?.Result;
if (result != null) // SelectedItem returns null if selection is empty.
{
bool hideWindow = result.Action != null && result.Action(new ActionContext
{
SpecialKeyState = GlobalHotkey.Instance.CheckModifiers()
});
if (hideWindow)
{
MainWindowVisibility = Visibility.Collapsed;
}
if (SelectedIsFromQueryResults())
{
_userSelectedRecord.Add(result);
_history.Add(result.OriginQuery.RawQuery);
}
else
{
SelectedResults = Results;
}
}
});
LoadContextMenuCommand = new RelayCommand(_ =>
{
if (SelectedIsFromQueryResults())
{
SelectedResults = ContextMenu;
}
else
{
SelectedResults = Results;
}
});
LoadHistoryCommand = new RelayCommand(_ =>
{
if (SelectedIsFromQueryResults())
{
SelectedResults = History;
History.SelectedIndex = _history.Items.Count - 1;
}
else
{
SelectedResults = Results;
}
});
}
#endregion
#region ViewModel Properties
public ResultsViewModel Results { get; private set; }
public ResultsViewModel ContextMenu { get; private set; }
public ResultsViewModel History { get; private set; }
private string _queryText;
public string QueryText
{
get { return _queryText; }
set
{
_queryText = value;
Query();
}
}
/// <summary>
/// we need move cursor to end when we manually changed query
/// but we don't want to move cursor to end when query is updated from TextBox
/// </summary>
/// <param name="queryText"></param>
public void ChangeQueryText(string queryText)
{
QueryTextCursorMovedToEnd = true;
QueryText = queryText;
}
public bool LastQuerySelected { get; set; }
public bool QueryTextCursorMovedToEnd { get; set; }
private ResultsViewModel _selectedResults;
private ResultsViewModel SelectedResults
{
get { return _selectedResults; }
set
{
_selectedResults = value;
if (SelectedIsFromQueryResults())
{
ContextMenu.Visbility = Visibility.Collapsed;
History.Visbility = Visibility.Collapsed;
ChangeQueryText(_queryTextBeforeLeaveResults);
}
else
{
Results.Visbility = Visibility.Collapsed;
_queryTextBeforeLeaveResults = QueryText;
// Because of Fody's optimization
// setter won't be called when property value is not changed.
// so we need manually call Query()
// http://stackoverflow.com/posts/25895769/revisions
if (string.IsNullOrEmpty(QueryText))
{
Query();
}
else
{
QueryText = string.Empty;
}
}
_selectedResults.Visbility = Visibility.Visible;
}
}
public Visibility ProgressBarVisibility { get; set; }
public Visibility MainWindowVisibility { get; set; }
public ICommand EscCommand { get; set; }
public ICommand SelectNextItemCommand { get; set; }
public ICommand SelectPrevItemCommand { get; set; }
public ICommand SelectNextPageCommand { get; set; }
public ICommand SelectPrevPageCommand { get; set; }
public ICommand SelectFirstResultCommand { get; set; }
public ICommand StartHelpCommand { get; set; }
public ICommand RefreshCommand { get; set; }
public ICommand LoadContextMenuCommand { get; set; }
public ICommand LoadHistoryCommand { get; set; }
public ICommand OpenResultCommand { get; set; }
#endregion
public void Query()
{
if (SelectedIsFromQueryResults())
{
QueryResults();
}
else if (ContextMenuSelected())
{
QueryContextMenu();
}
else if (HistorySelected())
{
QueryHistory();
}
}
private void QueryContextMenu()
{
const string id = "Context Menu ID";
var query = QueryText.ToLower().Trim();
ContextMenu.Clear();
var selected = Results.SelectedItem?.Result;
if (selected != null) // SelectedItem returns null if selection is empty.
{
var results = PluginManager.GetContextMenusForPlugin(selected);
results.Add(ContextMenuTopMost(selected));
results.Add(ContextMenuPluginInfo(selected.PluginID));
if (!string.IsNullOrEmpty(query))
{
var filtered = results.Where
(
r => StringMatcher.FuzzySearch(query, r.Title).IsSearchPrecisionScoreMet()
|| StringMatcher.FuzzySearch(query, r.SubTitle).IsSearchPrecisionScoreMet()
).ToList();
ContextMenu.AddResults(filtered, id);
}
else
{
ContextMenu.AddResults(results, id);
}
}
}
private void QueryHistory()
{
const string id = "Query History ID";
var query = QueryText.ToLower().Trim();
History.Clear();
var results = new List<Result>();
foreach (var h in _history.Items)
{
var title = _translator.GetTranslation("executeQuery");
var time = _translator.GetTranslation("lastExecuteTime");
var result = new Result
{
Title = string.Format(title, h.Query),
SubTitle = string.Format(time, h.ExecutedDateTime),
IcoPath = "Images\\history.png",
OriginQuery = new Query { RawQuery = h.Query },
Action = _ =>
{
SelectedResults = Results;
ChangeQueryText(h.Query);
return false;
}
};
results.Add(result);
}
if (!string.IsNullOrEmpty(query))
{
var filtered = results.Where
(
r => StringMatcher.FuzzySearch(query, r.Title).IsSearchPrecisionScoreMet() ||
StringMatcher.FuzzySearch(query, r.SubTitle).IsSearchPrecisionScoreMet()
).ToList();
History.AddResults(filtered, id);
}
else
{
History.AddResults(results, id);
}
}
private void QueryResults()
{
if (_updateSource != null && !_updateSource.IsCancellationRequested)
{
// first condition used for init run
// second condition used when task has already been canceled in last turn
_updateSource.Cancel();
Logger.WoxDebug($"cancel init {_updateSource.Token.GetHashCode()} {Thread.CurrentThread.ManagedThreadId} {QueryText}");
_updateSource.Dispose();
}
var source = new CancellationTokenSource();
_updateSource = source;
var token = source.Token;
ProgressBarVisibility = Visibility.Hidden;
var queryText = QueryText.Trim();
Task.Run(() =>
{
if (!string.IsNullOrEmpty(queryText))
{
if (token.IsCancellationRequested) { return; }
var query = QueryBuilder.Build(queryText, PluginManager.NonGlobalPlugins);
_lastQuery = query;
if (query != null)
{
// handle the exclusiveness of plugin using action keyword
if (token.IsCancellationRequested) { return; }
Task.Delay(200, token).ContinueWith(_ =>
{
Logger.WoxTrace($"progressbar visible 1 {token.GetHashCode()} {token.IsCancellationRequested} {Thread.CurrentThread.ManagedThreadId} {query} {ProgressBarVisibility}");
// start the progress bar if query takes more than 200 ms
if (!token.IsCancellationRequested)
{
ProgressBarVisibility = Visibility.Visible;
}
}, token);
if (token.IsCancellationRequested) { return; }
var plugins = PluginManager.AllPlugins;
var option = new ParallelOptions()
{
CancellationToken = token,
};
CountdownEvent countdown = new CountdownEvent(plugins.Count);
foreach (var plugin in plugins)
{
Task.Run(() =>
{
if (token.IsCancellationRequested)
{
Logger.WoxTrace($"canceled {token.GetHashCode()} {Thread.CurrentThread.ManagedThreadId} {queryText} {plugin.Metadata.Name}");
countdown.Signal();
return;
}
var results = PluginManager.QueryForPlugin(plugin, query);
if (token.IsCancellationRequested)
{
Logger.WoxTrace($"canceled {token.GetHashCode()} {Thread.CurrentThread.ManagedThreadId} {queryText} {plugin.Metadata.Name}");
countdown.Signal();
return;
}
_resultsQueue.Add(new ResultsForUpdate(results, plugin.Metadata, query, token, countdown));
}, token).ContinueWith(ErrorReporting.UnhandledExceptionHandleTask, TaskContinuationOptions.OnlyOnFaulted);
}
Task.Run(() =>
{
Logger.WoxTrace($"progressbar visible 2 {token.GetHashCode()} {token.IsCancellationRequested} {Thread.CurrentThread.ManagedThreadId} {query} {ProgressBarVisibility}");
// wait all plugins has been processed
try
{
countdown.Wait(token);
}
catch (OperationCanceledException)
{
// todo: why we need hidden here and why progress bar is not working
ProgressBarVisibility = Visibility.Hidden;
return;
}
if (!token.IsCancellationRequested)
{
// used to cancel previous progress bar visible task
source.Cancel();
source.Dispose();
// update to hidden if this is still the current query
ProgressBarVisibility = Visibility.Hidden;
}
});
}
}
else
{
Results.Clear();
Results.Visbility = Visibility.Collapsed;
}
}, token).ContinueWith(ErrorReporting.UnhandledExceptionHandleTask, TaskContinuationOptions.OnlyOnFaulted);
}
private void Refresh()
{
PluginManager.ReloadData();
}
private Result ContextMenuTopMost(Result result)
{
Result menu;
if (_topMostRecord.IsTopMost(result))
{
menu = new Result
{
Title = InternationalizationManager.Instance.GetTranslation("cancelTopMostInThisQuery"),
IcoPath = "Images\\down.png",
PluginDirectory = Constant.ProgramDirectory,
Action = _ =>
{
_topMostRecord.Remove(result);
App.API.ShowMsg("Success");
return false;
}
};
}
else
{
menu = new Result
{
Title = InternationalizationManager.Instance.GetTranslation("setAsTopMostInThisQuery"),
IcoPath = "Images\\up.png",
PluginDirectory = Constant.ProgramDirectory,
Action = _ =>
{
_topMostRecord.AddOrUpdate(result);
App.API.ShowMsg("Success");
return false;
}
};
}
return menu;
}
private Result ContextMenuPluginInfo(string id)
{
var metadata = PluginManager.GetPluginForId(id).Metadata;
var translator = InternationalizationManager.Instance;
var author = translator.GetTranslation("author");
var website = translator.GetTranslation("website");
var version = translator.GetTranslation("version");
var plugin = translator.GetTranslation("plugin");
var title = $"{plugin}: {metadata.Name}";
var icon = metadata.IcoPath;
var subtitle = $"{author}: {metadata.Author}, {website}: {metadata.Website} {version}: {metadata.Version}";
var menu = new Result
{
Title = title,
IcoPath = icon,
SubTitle = subtitle,
PluginDirectory = metadata.PluginDirectory,
Action = _ => false
};
return menu;
}
private bool SelectedIsFromQueryResults()
{
var selected = SelectedResults == Results;
return selected;
}
private bool ContextMenuSelected()
{
var selected = SelectedResults == ContextMenu;
return selected;
}
private bool HistorySelected()
{
var selected = SelectedResults == History;
return selected;
}
#region Hotkey
private void SetHotkey(string hotkeyStr, EventHandler<HotkeyEventArgs> action)
{
var hotkey = new HotkeyModel(hotkeyStr);
SetHotkey(hotkey, action);
}
private void SetHotkey(HotkeyModel hotkey, EventHandler<HotkeyEventArgs> action)
{
string hotkeyStr = hotkey.ToString();
try
{
HotkeyManager.Current.AddOrReplace(hotkeyStr, hotkey.CharKey, hotkey.ModifierKeys, action);
}
catch (Exception)
{
string errorMsg =
string.Format(InternationalizationManager.Instance.GetTranslation("registerHotkeyFailed"), hotkeyStr);
MessageBox.Show(errorMsg);
}
}
public void RemoveHotkey(string hotkeyStr)
{
if (!string.IsNullOrEmpty(hotkeyStr))
{
HotkeyManager.Current.Remove(hotkeyStr);
}
}
/// <summary>
/// Checks if Wox should ignore any hotkeys
/// </summary>
/// <returns></returns>
private bool ShouldIgnoreHotkeys()
{
//double if to omit calling win32 function
if (_settings.IgnoreHotkeysOnFullscreen)
if (WindowsInteropHelper.IsWindowFullscreen())
return true;
return false;
}
private void SetCustomPluginHotkey()
{
if (_settings.CustomPluginHotkeys == null) return;
foreach (CustomPluginHotkey hotkey in _settings.CustomPluginHotkeys)
{
SetHotkey(hotkey.Hotkey, (s, e) =>
{
if (ShouldIgnoreHotkeys()) return;
MainWindowVisibility = Visibility.Visible;
ChangeQueryText(hotkey.ActionKeyword);
});
}
}
private void OnHotkey(object sender, HotkeyEventArgs e)
{
if (!ShouldIgnoreHotkeys())
{
if (_settings.LastQueryMode == LastQueryMode.Empty)
{
ChangeQueryText(string.Empty);
}
else if (_settings.LastQueryMode == LastQueryMode.Preserved)
{
LastQuerySelected = true;
}
else if (_settings.LastQueryMode == LastQueryMode.Selected)
{
LastQuerySelected = false;
}
else
{
throw new ArgumentException($"wrong LastQueryMode: <{_settings.LastQueryMode}>");
}
ToggleWox();
e.Handled = true;
}
}
private void ToggleWox()
{
if (MainWindowVisibility != Visibility.Visible)
{
MainWindowVisibility = Visibility.Visible;
}
else
{
MainWindowVisibility = Visibility.Collapsed;
}
}
#endregion
#region Public Methods
public void Save()
{
if (!_saved)
{
_historyItemsStorage.Save();
_userSelectedRecordStorage.Save();
_topMostRecordStorage.Save();
_saved = true;
}
}
public void UpdateResultView(List<Result> list, PluginMetadata metadata, Query originQuery, CancellationToken token)
{
CountdownEvent countdown = new CountdownEvent(1);
List<ResultsForUpdate> updates = new List<ResultsForUpdate>()
{
new ResultsForUpdate(list, metadata, originQuery, token, countdown)
};
UpdateResultView(updates);
}
/// <summary>
/// To avoid deadlock, this method should not called from main thread
/// </summary>
public void UpdateResultView(List<ResultsForUpdate> updates)
{
foreach (ResultsForUpdate update in updates)
{
Logger.WoxTrace($"{update.Metadata.Name}:{update.Query.RawQuery}");
foreach (var result in update.Results)
{
if (update.Token.IsCancellationRequested) { return; }
if (_topMostRecord.IsTopMost(result))
{
result.Score = int.MaxValue;
}
else if (!update.Metadata.KeepResultRawScore)
{
result.Score += _userSelectedRecord.GetSelectedCount(result) * 10;
}
else
{
result.Score = result.Score;
}
}
}
Results.AddResults(updates);
if (Results.Visbility != Visibility.Visible && Results.Count > 0)
{
Results.Visbility = Visibility.Visible;
}
}
#endregion
}
}
| |
namespace Banshee.Base.Winforms.Gui
{
partial class PreferencesDialog
{
/// <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.library_location_label = new System.Windows.Forms.Label();
this.library_reset = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.copy_on_import = new System.Windows.Forms.CheckBox();
this.write_metadata = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.error_correction = new System.Windows.Forms.CheckBox();
this.cd_importing_profile_box = new System.Windows.Forms.ComboBox();
this.library_location_chooser = new System.Windows.Forms.ComboBox();
this.folder_box = new System.Windows.Forms.ComboBox();
this.file_box = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.example_path = new System.Windows.Forms.Label();
this.button1 = new ComponentFactory.Krypton.Toolkit.KryptonButton();
((System.ComponentModel.ISupportInitialize)(this.library_reset)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.button1)).BeginInit();
this.SuspendLayout();
//
// library_location_label
//
this.library_location_label.AutoSize = true;
this.library_location_label.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.library_location_label.Location = new System.Drawing.Point(15, 8);
this.library_location_label.Name = "library_location_label";
this.library_location_label.Size = new System.Drawing.Size(83, 13);
this.library_location_label.TabIndex = 0;
this.library_location_label.Text = "Media Library";
//
// library_reset
//
this.library_reset.DirtyPaletteCounter = 1;
this.library_reset.Location = new System.Drawing.Point(197, 26);
this.library_reset.Name = "library_reset";
this.library_reset.Size = new System.Drawing.Size(75, 24);
this.library_reset.TabIndex = 1;
this.library_reset.Text = "Reset";
this.library_reset.Values.ExtraText = "";
this.library_reset.Values.Image = null;
this.library_reset.Values.ImageStates.ImageCheckedNormal = null;
this.library_reset.Values.ImageStates.ImageCheckedPressed = null;
this.library_reset.Values.ImageStates.ImageCheckedTracking = null;
this.library_reset.Values.Text = "Reset";
//
// copy_on_import
//
this.copy_on_import.AutoSize = true;
this.copy_on_import.Location = new System.Drawing.Point(20, 58);
this.copy_on_import.Name = "copy_on_import";
this.copy_on_import.Size = new System.Drawing.Size(216, 17);
this.copy_on_import.TabIndex = 2;
this.copy_on_import.Text = "Co&py files to music folder when importing";
this.copy_on_import.UseVisualStyleBackColor = true;
this.copy_on_import.CheckedChanged += new System.EventHandler(this.copy_on_import_CheckedChanged);
//
// write_metadata
//
this.write_metadata.AutoSize = true;
this.write_metadata.Location = new System.Drawing.Point(21, 89);
this.write_metadata.Name = "write_metadata";
this.write_metadata.Size = new System.Drawing.Size(131, 17);
this.write_metadata.TabIndex = 3;
this.write_metadata.Text = "Write &metadata to files";
this.write_metadata.UseVisualStyleBackColor = true;
this.write_metadata.CheckedChanged += new System.EventHandler(this.write_metadata_CheckedChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(15, 123);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(146, 13);
this.label1.TabIndex = 4;
this.label1.Text = "File System Organization";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(15, 145);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(85, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Folder hierarchy:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(17, 171);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(55, 13);
this.label3.TabIndex = 6;
this.label3.Text = "File name:";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(17, 217);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(80, 13);
this.label4.TabIndex = 7;
this.label4.Text = "CD Importing";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(18, 239);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(74, 13);
this.label5.TabIndex = 8;
this.label5.Text = "Output format:";
//
// error_correction
//
this.error_correction.AutoSize = true;
this.error_correction.Location = new System.Drawing.Point(18, 268);
this.error_correction.Name = "error_correction";
this.error_correction.Size = new System.Drawing.Size(193, 17);
this.error_correction.TabIndex = 9;
this.error_correction.Text = "Use error correction when importing";
this.error_correction.UseVisualStyleBackColor = true;
this.error_correction.CheckedChanged += new System.EventHandler(this.error_correction_CheckedChanged);
//
// cd_importing_profile_box
//
this.cd_importing_profile_box.FormattingEnabled = true;
this.cd_importing_profile_box.Location = new System.Drawing.Point(18, 291);
this.cd_importing_profile_box.Name = "cd_importing_profile_box";
this.cd_importing_profile_box.Size = new System.Drawing.Size(121, 21);
this.cd_importing_profile_box.TabIndex = 10;
//
// library_location_chooser
//
this.library_location_chooser.FormattingEnabled = true;
this.library_location_chooser.Location = new System.Drawing.Point(22, 28);
this.library_location_chooser.Name = "library_location_chooser";
this.library_location_chooser.Size = new System.Drawing.Size(169, 21);
this.library_location_chooser.TabIndex = 11;
this.library_location_chooser.SelectionChangeCommitted += new System.EventHandler(this.library_location_chooser_SelectionChangeCommitted);
//
// folder_box
//
this.folder_box.FormattingEnabled = true;
this.folder_box.Location = new System.Drawing.Point(151, 142);
this.folder_box.Name = "folder_box";
this.folder_box.Size = new System.Drawing.Size(121, 21);
this.folder_box.TabIndex = 12;
this.folder_box.SelectionChangeCommitted += new System.EventHandler(this.folder_box_SelectionChangeCommitted);
//
// file_box
//
this.file_box.FormattingEnabled = true;
this.file_box.Location = new System.Drawing.Point(151, 168);
this.file_box.Name = "file_box";
this.file_box.Size = new System.Drawing.Size(121, 21);
this.file_box.TabIndex = 13;
this.file_box.SelectionChangeCommitted += new System.EventHandler(this.file_box_SelectionChangeCommitted);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(156, 239);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(30, 13);
this.label6.TabIndex = 14;
this.label6.Text = ".mp3";
//
// example_path
//
this.example_path.AutoSize = true;
this.example_path.Location = new System.Drawing.Point(19, 193);
this.example_path.Name = "example_path";
this.example_path.Size = new System.Drawing.Size(73, 13);
this.example_path.TabIndex = 15;
this.example_path.Text = "example_path";
//
// button1
//
this.button1.DirtyPaletteCounter = 1;
this.button1.Location = new System.Drawing.Point(197, 291);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 24);
this.button1.TabIndex = 16;
this.button1.Text = "Close";
this.button1.Values.ExtraText = "";
this.button1.Values.Image = null;
this.button1.Values.ImageStates.ImageCheckedNormal = null;
this.button1.Values.ImageStates.ImageCheckedPressed = null;
this.button1.Values.ImageStates.ImageCheckedTracking = null;
this.button1.Values.Text = "Close";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// PreferencesDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 328);
this.Controls.Add(this.button1);
this.Controls.Add(this.example_path);
this.Controls.Add(this.label6);
this.Controls.Add(this.file_box);
this.Controls.Add(this.folder_box);
this.Controls.Add(this.library_location_chooser);
this.Controls.Add(this.cd_importing_profile_box);
this.Controls.Add(this.error_correction);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.write_metadata);
this.Controls.Add(this.copy_on_import);
this.Controls.Add(this.library_reset);
this.Controls.Add(this.library_location_label);
this.Name = "PreferencesDialog";
this.Text = "Preferences";
this.Load += new System.EventHandler(this.PreferencesDialog_Load);
((System.ComponentModel.ISupportInitialize)(this.library_reset)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.button1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label library_location_label;
private ComponentFactory.Krypton.Toolkit.KryptonButton library_reset;
private System.Windows.Forms.CheckBox copy_on_import;
private System.Windows.Forms.CheckBox write_metadata;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.CheckBox error_correction;
private System.Windows.Forms.ComboBox cd_importing_profile_box;
private System.Windows.Forms.ComboBox library_location_chooser;
private System.Windows.Forms.ComboBox folder_box;
private System.Windows.Forms.ComboBox file_box;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label example_path;
private ComponentFactory.Krypton.Toolkit.KryptonButton button1;
}
}
| |
namespace Zu.TypeScript.TsTypes
{
public enum SyntaxKind
{
Unknown,
EndOfFileToken,
SingleLineCommentTrivia,
MultiLineCommentTrivia,
NewLineTrivia,
WhitespaceTrivia,
// We detect and preserve #! on the first line
ShebangTrivia,
// We detect and provide better error recovery when we encounter a git merge marker. This
// allows us to edit files with git-conflict markers in them in a much more pleasant manner.
ConflictMarkerTrivia,
// Literals
NumericLiteral,
StringLiteral,
JsxText,
RegularExpressionLiteral,
NoSubstitutionTemplateLiteral,
// Pseudo-literals
TemplateHead,
TemplateMiddle,
TemplateTail,
// Punctuation
OpenBraceToken,
CloseBraceToken,
OpenParenToken,
CloseParenToken,
OpenBracketToken,
CloseBracketToken,
DotToken,
DotDotDotToken,
SemicolonToken,
CommaToken,
LessThanToken,
LessThanSlashToken,
GreaterThanToken,
LessThanEqualsToken,
GreaterThanEqualsToken,
EqualsEqualsToken,
ExclamationEqualsToken,
EqualsEqualsEqualsToken,
ExclamationEqualsEqualsToken,
EqualsGreaterThanToken,
PlusToken,
MinusToken,
AsteriskToken,
AsteriskAsteriskToken,
SlashToken,
PercentToken,
PlusPlusToken,
MinusMinusToken,
LessThanLessThanToken,
GreaterThanGreaterThanToken,
GreaterThanGreaterThanGreaterThanToken,
AmpersandToken,
BarToken,
CaretToken,
ExclamationToken,
TildeToken,
AmpersandAmpersandToken,
BarBarToken,
QuestionToken,
ColonToken,
AtToken,
// Assignments
EqualsToken,
PlusEqualsToken,
MinusEqualsToken,
AsteriskEqualsToken,
AsteriskAsteriskEqualsToken,
SlashEqualsToken,
PercentEqualsToken,
LessThanLessThanEqualsToken,
GreaterThanGreaterThanEqualsToken,
GreaterThanGreaterThanGreaterThanEqualsToken,
AmpersandEqualsToken,
BarEqualsToken,
CaretEqualsToken,
// Identifiers
Identifier,
// Reserved words
BreakKeyword,
CaseKeyword,
CatchKeyword,
ClassKeyword,
ConstKeyword,
ContinueKeyword,
DebuggerKeyword,
DefaultKeyword,
DeleteKeyword,
DoKeyword,
ElseKeyword,
EnumKeyword,
ExportKeyword,
ExtendsKeyword,
FalseKeyword,
FinallyKeyword,
ForKeyword,
FunctionKeyword,
IfKeyword,
ImportKeyword,
InKeyword,
InstanceOfKeyword,
NewKeyword,
NullKeyword,
ReturnKeyword,
SuperKeyword,
SwitchKeyword,
ThisKeyword,
ThrowKeyword,
TrueKeyword,
TryKeyword,
TypeOfKeyword,
VarKeyword,
VoidKeyword,
WhileKeyword,
WithKeyword,
// Strict mode reserved words
ImplementsKeyword,
InterfaceKeyword,
LetKeyword,
PackageKeyword,
PrivateKeyword,
ProtectedKeyword,
PublicKeyword,
StaticKeyword,
YieldKeyword,
// Contextual keywords
AbstractKeyword,
AsKeyword,
AnyKeyword,
AsyncKeyword,
AwaitKeyword,
BooleanKeyword,
ConstructorKeyword,
DeclareKeyword,
GetKeyword,
IsKeyword,
KeyOfKeyword,
ModuleKeyword,
NamespaceKeyword,
NeverKeyword,
ReadonlyKeyword,
RequireKeyword,
NumberKeyword,
ObjectKeyword,
SetKeyword,
StringKeyword,
SymbolKeyword,
TypeKeyword,
UndefinedKeyword,
FromKeyword,
GlobalKeyword,
OfKeyword, // LastKeyword and LastToken
// Parse tree nodes
// Names
QualifiedName,
ComputedPropertyName,
// Signature elements
TypeParameter,
Parameter,
Decorator,
// TypeMember
PropertySignature,
PropertyDeclaration,
MethodSignature,
MethodDeclaration,
Constructor,
GetAccessor,
SetAccessor,
CallSignature,
ConstructSignature,
IndexSignature,
// Type
TypePredicate,
TypeReference,
FunctionType,
ConstructorType,
TypeQuery,
TypeLiteral,
ArrayType,
TupleType,
UnionType,
IntersectionType,
ParenthesizedType,
ThisType,
TypeOperator,
IndexedAccessType,
MappedType,
LiteralType,
// Binding patterns
ObjectBindingPattern,
ArrayBindingPattern,
BindingElement,
// Expression
ArrayLiteralExpression,
ObjectLiteralExpression,
PropertyAccessExpression,
ElementAccessExpression,
CallExpression,
NewExpression,
TaggedTemplateExpression,
TypeAssertionExpression,
ParenthesizedExpression,
FunctionExpression,
ArrowFunction,
DeleteExpression,
TypeOfExpression,
VoidExpression,
AwaitExpression,
PrefixUnaryExpression,
PostfixUnaryExpression,
BinaryExpression,
ConditionalExpression,
TemplateExpression,
YieldExpression,
SpreadElement,
ClassExpression,
OmittedExpression,
ExpressionWithTypeArguments,
AsExpression,
NonNullExpression,
MetaProperty,
// Misc
TemplateSpan,
SemicolonClassElement,
// Element
Block,
VariableStatement,
EmptyStatement,
ExpressionStatement,
IfStatement,
DoStatement,
WhileStatement,
ForStatement,
ForInStatement,
ForOfStatement,
ContinueStatement,
BreakStatement,
ReturnStatement,
WithStatement,
SwitchStatement,
LabeledStatement,
ThrowStatement,
TryStatement,
DebuggerStatement,
VariableDeclaration,
VariableDeclarationList,
FunctionDeclaration,
ClassDeclaration,
InterfaceDeclaration,
TypeAliasDeclaration,
EnumDeclaration,
ModuleDeclaration,
ModuleBlock,
CaseBlock,
NamespaceExportDeclaration,
ImportEqualsDeclaration,
ImportDeclaration,
ImportClause,
NamespaceImport,
NamedImports,
ImportSpecifier,
ExportAssignment,
ExportDeclaration,
NamedExports,
ExportSpecifier,
MissingDeclaration,
// Module references
ExternalModuleReference,
// JSX
JsxElement,
JsxSelfClosingElement,
JsxOpeningElement,
JsxClosingElement,
JsxAttribute,
JsxAttributes,
JsxSpreadAttribute,
JsxExpression,
// Clauses
CaseClause,
DefaultClause,
HeritageClause,
CatchClause,
// Property assignments
PropertyAssignment,
ShorthandPropertyAssignment,
SpreadAssignment,
// Enum
EnumMember,
// Top-level nodes
SourceFile,
Bundle,
// JSDoc nodes
JsDocTypeExpression,
// The * type
JsDocAllType,
// The ? type
JsDocUnknownType,
JsDocArrayType,
JsDocUnionType,
JsDocTupleType,
JsDocNullableType,
JsDocNonNullableType,
JsDocRecordType,
JsDocRecordMember,
JsDocTypeReference,
JsDocOptionalType,
JsDocFunctionType,
JsDocVariadicType,
JsDocConstructorType,
JsDocThisType,
JsDocComment,
JsDocTag,
JsDocAugmentsTag,
JsDocParameterTag,
JsDocReturnTag,
JsDocTypeTag,
JsDocTemplateTag,
JsDocTypedefTag,
JsDocPropertyTag,
JsDocTypeLiteral,
JsDocLiteralType,
// Synthesized list
SyntaxList,
// Transformation nodes
NotEmittedStatement,
PartiallyEmittedExpression,
MergeDeclarationMarker,
EndOfDeclarationMarker,
// Enum value count
Count,
// Markers
FirstAssignment = EqualsToken,
LastAssignment = CaretEqualsToken,
FirstCompoundAssignment = PlusEqualsToken,
LastCompoundAssignment = CaretEqualsToken,
FirstReservedWord = BreakKeyword,
LastReservedWord = WithKeyword,
FirstKeyword = BreakKeyword,
LastKeyword = OfKeyword,
FirstFutureReservedWord = ImplementsKeyword,
LastFutureReservedWord = YieldKeyword,
FirstTypeNode = TypePredicate,
LastTypeNode = LiteralType,
FirstPunctuation = OpenBraceToken,
LastPunctuation = CaretEqualsToken,
FirstToken = Unknown,
LastToken = LastKeyword,
FirstTriviaToken = SingleLineCommentTrivia,
LastTriviaToken = ConflictMarkerTrivia,
FirstLiteralToken = NumericLiteral,
LastLiteralToken = NoSubstitutionTemplateLiteral,
FirstTemplateToken = NoSubstitutionTemplateLiteral,
LastTemplateToken = TemplateTail,
FirstBinaryOperator = LessThanToken,
LastBinaryOperator = CaretEqualsToken,
FirstNode = QualifiedName,
FirstJsDocNode = JsDocTypeExpression,
LastJsDocNode = JsDocLiteralType,
FirstJsDocTagNode = JsDocComment,
LastJsDocTagNode = JsDocLiteralType
}
}
| |
using System;
using System.Diagnostics;
namespace Lucene.Net.Search
{
/*
* 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 ArrayUtil = Lucene.Net.Util.ArrayUtil;
using ByteBlockPool = Lucene.Net.Util.ByteBlockPool;
using BytesRef = Lucene.Net.Util.BytesRef;
using BytesRefHash = Lucene.Net.Util.BytesRefHash;
using IndexReader = Lucene.Net.Index.IndexReader;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
using RewriteMethod = Lucene.Net.Search.MultiTermQuery.RewriteMethod;
using Term = Lucene.Net.Index.Term;
using TermContext = Lucene.Net.Index.TermContext;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using TermState = Lucene.Net.Index.TermState;
/// <summary>
/// Base rewrite method that translates each term into a query, and keeps
/// the scores as computed by the query.
/// <para/>
/// @lucene.internal - Only public to be accessible by spans package.
/// </summary>
public abstract class ScoringRewrite<Q> : TermCollectingRewrite<Q> where Q : Query
{
/// <summary>
/// A rewrite method that first translates each term into
/// <see cref="Occur.SHOULD"/> clause in a
/// <see cref="BooleanQuery"/>, and keeps the scores as computed by the
/// query. Note that typically such scores are
/// meaningless to the user, and require non-trivial CPU
/// to compute, so it's almost always better to use
/// <see cref="MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT"/> instead.
///
/// <para/><b>NOTE</b>: this rewrite method will hit
/// <see cref="BooleanQuery.TooManyClausesException"/> if the number of terms
/// exceeds <see cref="BooleanQuery.MaxClauseCount"/>.
/// </summary>
/// <seealso cref="MultiTermQuery.MultiTermRewriteMethod"/>
public static readonly ScoringRewrite<BooleanQuery> SCORING_BOOLEAN_QUERY_REWRITE = new ScoringRewriteAnonymousInnerClassHelper();
private class ScoringRewriteAnonymousInnerClassHelper : ScoringRewrite<BooleanQuery>
{
public ScoringRewriteAnonymousInnerClassHelper()
{
}
protected override BooleanQuery GetTopLevelQuery()
{
return new BooleanQuery(true);
}
protected override void AddClause(BooleanQuery topLevel, Term term, int docCount, float boost, TermContext states)
{
TermQuery tq = new TermQuery(term, states);
tq.Boost = boost;
topLevel.Add(tq, Occur.SHOULD);
}
protected override void CheckMaxClauseCount(int count)
{
if (count > BooleanQuery.MaxClauseCount)
{
throw new BooleanQuery.TooManyClausesException();
}
}
}
/// <summary>
/// Like <see cref="SCORING_BOOLEAN_QUERY_REWRITE"/> except
/// scores are not computed. Instead, each matching
/// document receives a constant score equal to the
/// query's boost.
///
/// <para/><b>NOTE</b>: this rewrite method will hit
/// <see cref="BooleanQuery.TooManyClausesException"/> if the number of terms
/// exceeds <see cref="BooleanQuery.MaxClauseCount"/>.
/// </summary>
/// <seealso cref="MultiTermQuery.MultiTermRewriteMethod"/>
public static readonly RewriteMethod CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE = new RewriteMethodAnonymousInnerClassHelper();
private class RewriteMethodAnonymousInnerClassHelper : RewriteMethod
{
public RewriteMethodAnonymousInnerClassHelper()
{
}
public override Query Rewrite(IndexReader reader, MultiTermQuery query)
{
BooleanQuery bq = (BooleanQuery)SCORING_BOOLEAN_QUERY_REWRITE.Rewrite(reader, query);
// strip the scores off
Query result = new ConstantScoreQuery(bq);
result.Boost = query.Boost;
return result;
}
}
/// <summary>
/// This method is called after every new term to check if the number of max clauses
/// (e.g. in <see cref="BooleanQuery"/>) is not exceeded. Throws the corresponding <see cref="Exception"/>.
/// </summary>
protected abstract void CheckMaxClauseCount(int count);
public override Query Rewrite(IndexReader reader, MultiTermQuery query)
{
var result = GetTopLevelQuery();
ParallelArraysTermCollector col = new ParallelArraysTermCollector(this);
CollectTerms(reader, query, col);
int size = col.terms.Count;
if (size > 0)
{
int[] sort = col.terms.Sort(col.termsEnum.Comparer);
float[] boost = col.array.boost;
TermContext[] termStates = col.array.termState;
for (int i = 0; i < size; i++)
{
int pos = sort[i];
Term term = new Term(query.Field, col.terms.Get(pos, new BytesRef()));
Debug.Assert(reader.DocFreq(term) == termStates[pos].DocFreq);
AddClause(result, term, termStates[pos].DocFreq, query.Boost * boost[pos], termStates[pos]);
}
}
return result;
}
internal sealed class ParallelArraysTermCollector : TermCollector
{
internal void InitializeInstanceFields()
{
terms = new BytesRefHash(new ByteBlockPool(new ByteBlockPool.DirectAllocator()), 16, array);
}
private readonly ScoringRewrite<Q> outerInstance;
public ParallelArraysTermCollector(ScoringRewrite<Q> outerInstance)
{
this.outerInstance = outerInstance;
InitializeInstanceFields();
}
internal readonly TermFreqBoostByteStart array = new TermFreqBoostByteStart(16);
internal BytesRefHash terms;
internal TermsEnum termsEnum;
private IBoostAttribute boostAtt;
public override void SetNextEnum(TermsEnum termsEnum)
{
this.termsEnum = termsEnum;
this.boostAtt = termsEnum.Attributes.AddAttribute<IBoostAttribute>();
}
public override bool Collect(BytesRef bytes)
{
int e = terms.Add(bytes);
TermState state = termsEnum.GetTermState();
Debug.Assert(state != null);
if (e < 0)
{
// duplicate term: update docFreq
int pos = (-e) - 1;
array.termState[pos].Register(state, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq);
Debug.Assert(array.boost[pos] == boostAtt.Boost, "boost should be equal in all segment TermsEnums");
}
else
{
// new entry: we populate the entry initially
array.boost[e] = boostAtt.Boost;
array.termState[e] = new TermContext(m_topReaderContext, state, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq);
outerInstance.CheckMaxClauseCount(terms.Count);
}
return true;
}
}
/// <summary>
/// Special implementation of <see cref="BytesRefHash.BytesStartArray"/> that keeps parallel arrays for boost and docFreq </summary>
internal sealed class TermFreqBoostByteStart : BytesRefHash.DirectBytesStartArray
{
internal float[] boost;
internal TermContext[] termState;
public TermFreqBoostByteStart(int initSize)
: base(initSize)
{
}
public override int[] Init()
{
int[] ord = base.Init();
boost = new float[ArrayUtil.Oversize(ord.Length, RamUsageEstimator.NUM_BYTES_SINGLE)];
termState = new TermContext[ArrayUtil.Oversize(ord.Length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
Debug.Assert(termState.Length >= ord.Length && boost.Length >= ord.Length);
return ord;
}
public override int[] Grow()
{
int[] ord = base.Grow();
boost = ArrayUtil.Grow(boost, ord.Length);
if (termState.Length < ord.Length)
{
TermContext[] tmpTermState = new TermContext[ArrayUtil.Oversize(ord.Length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
Array.Copy(termState, 0, tmpTermState, 0, termState.Length);
termState = tmpTermState;
}
Debug.Assert(termState.Length >= ord.Length && boost.Length >= ord.Length);
return ord;
}
public override int[] Clear()
{
boost = null;
termState = null;
return base.Clear();
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal {
public partial class MessageBox {
/// <summary>
/// tblMessageBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl tblMessageBox;
/// <summary>
/// litMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litMessage;
/// <summary>
/// litDescription control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litDescription;
/// <summary>
/// rowTechnicalDetails control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl rowTechnicalDetails;
/// <summary>
/// secTechnicalDetails control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secTechnicalDetails;
/// <summary>
/// TechnicalDetailsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel TechnicalDetailsPanel;
/// <summary>
/// tblTechnicalDetails control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTable tblTechnicalDetails;
/// <summary>
/// lblPageUrl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblPageUrl;
/// <summary>
/// litPageUrl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litPageUrl;
/// <summary>
/// lblLoggedUser control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblLoggedUser;
/// <summary>
/// litLoggedUser control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litLoggedUser;
/// <summary>
/// lblWorkOnBehalf control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblWorkOnBehalf;
/// <summary>
/// litSelectedUser control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litSelectedUser;
/// <summary>
/// lblSpace control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSpace;
/// <summary>
/// litPackageName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litPackageName;
/// <summary>
/// lblStackTrace control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblStackTrace;
/// <summary>
/// litStackTrace control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litStackTrace;
/// <summary>
/// secSendReport control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secSendReport;
/// <summary>
/// SendReportPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel SendReportPanel;
/// <summary>
/// lblFrom control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFrom;
/// <summary>
/// litSendFrom control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litSendFrom;
/// <summary>
/// lblTo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblTo;
/// <summary>
/// litSendTo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litSendTo;
/// <summary>
/// lblCC control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblCC;
/// <summary>
/// litSendCC control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litSendCC;
/// <summary>
/// lblSubject control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSubject;
/// <summary>
/// litSendSubject control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litSendSubject;
/// <summary>
/// lblComments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblComments;
/// <summary>
/// txtSendComments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSendComments;
/// <summary>
/// btnSend control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnSend;
/// <summary>
/// lblSentMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSentMessage;
}
}
| |
/*
Copyright (c) 2006 Tomas Matousek and Ladislav Prosek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using PHP.Core.AST;
using PHP.Core.Emit;
using PHP.Core.Parsers;
namespace PHP.Core.Reflection
{
#region DConstantDesc
public sealed class DConstantDesc : DMemberDesc
{
/// <summary>
/// Written-up by the analyzer if the value is evaluable (literals only).
/// </summary>
public object LiteralValue
{
get
{
Debug.Assert(!ValueIsDeferred, "This constant's literal value cannot be accessed directly. You have to read its realField in runtime after you initialize static fields.");
return literalValue;
}
internal /* friend DConstant */ set
{
Debug.Assert(value is int || value is string || value == null || value is bool || value is double || value is long);
this.literalValue = value;
this.ValueIsDeferred = false;
}
}
private object literalValue;
public GlobalConstant GlobalConstant { get { return (GlobalConstant)Member; } }
public ClassConstant ClassConstant { get { return (ClassConstant)Member; } }
#region Construction
/// <summary>
/// Used by compiler for global constants.
/// </summary>
public DConstantDesc(DModule/*!*/ declaringModule, PhpMemberAttributes memberAttributes, object literalValue)
: base(declaringModule.GlobalType.TypeDesc, memberAttributes | PhpMemberAttributes.Static)
{
Debug.Assert(declaringModule != null);
this.literalValue = literalValue;
}
/// <summary>
/// Used by compiler for class constants.
/// </summary>
public DConstantDesc(DTypeDesc/*!*/ declaringType, PhpMemberAttributes memberAttributes, object literalValue)
: base(declaringType, memberAttributes | PhpMemberAttributes.Static)
{
Debug.Assert(declaringType != null);
this.literalValue = literalValue;
}
#endregion
public override string MakeFullName()
{
Debug.Fail("Not Supported");
return null;
}
public override string MakeFullGenericName()
{
Debug.Fail("Not Supported");
return null;
}
#region Run-Time Operations
/// <summary>
/// <c>True</c> if value of this constant is deferred to runtime; hence it must be read from corresponding static field every time.
/// </summary>
internal bool ValueIsDeferred { get; set; }
/// <summary>
/// Read value of this constant.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public object GetValue(ScriptContext/*!*/ context)
{
if (ValueIsDeferred)
{
if (Member.GetType() == typeof(ClassConstant) && DeclaringType.GetType() == typeof(PhpTypeDesc))
{
((PhpTypeDesc)DeclaringType).EnsureThreadStaticFieldsInitialized(context);
return ((ClassConstant)Member).GetValue();
}
if (memberAttributes.GetType() == typeof(GlobalConstant))
{
// TODO: initialize deferred global constant
return ((ClassConstant)Member).GetValue();
}
Debug.Fail("Uncaught constant type.");
}
//
return this.LiteralValue;
}
#endregion
}
#endregion
#region DConstant
public abstract class DConstant : DMember
{
public sealed override bool IsDefinite { get { return IsIdentityDefinite; } }
public DConstantDesc/*!*/ ConstantDesc { get { return (DConstantDesc)memberDesc; } }
/// <summary>
/// Whether the value of the constant is known and stored in the constant-desc.
/// </summary>
public abstract bool HasValue { get; }
/// <summary>
/// Constant value. Valid only if <see cref="HasValue"/> is <B>true</B>.
/// </summary>
public object Value { get { return ConstantDesc.LiteralValue; } }
#region Construction
/// <summary>
/// Used by known constant subclasses.
/// </summary>
public DConstant(DConstantDesc/*!*/ constantDesc)
: base(constantDesc)
{
Debug.Assert(constantDesc != null);
}
/// <summary>
/// Used by unknown constants subclasses.
/// </summary>
public DConstant(string/*!*/ fullName)
: base(null, fullName)
{
Debug.Assert(IsUnknown);
}
#endregion
internal virtual void ReportCircularDefinition(ErrorSink/*!*/ errors)
{
Debug.Fail(null);
}
internal abstract PhpTypeCode EmitGet(CodeGenerator/*!*/ codeGenerator, ConstructedType constructedType,
bool runtimeVisibilityCheck, string fallbackName);
}
#endregion
#region UnknownClassConstant, UnknownGlobalConstant
public sealed class UnknownClassConstant : DConstant
{
public override bool IsUnknown { get { return true; } }
public override bool IsIdentityDefinite { get { return false; } }
public override bool HasValue { get { return false; } }
public override DType/*!*/ DeclaringType { get { return declaringType; } }
private readonly DType/*!*/ declaringType;
public UnknownClassConstant(DType/*!*/ declaringType, string/*!*/ fullName)
: base(fullName)
{
Debug.Assert(fullName != null);
this.declaringType = declaringType;
}
public override string GetFullName()
{
return FullName;
}
internal override PhpTypeCode EmitGet(CodeGenerator/*!*/ codeGenerator, ConstructedType constructedType,
bool runtimeVisibilityCheck, string fallbackName)
{
Debug.Assert(fallbackName == null);
codeGenerator.EmitGetConstantValueOperator(declaringType, this.FullName, null);
return PhpTypeCode.Object;
}
}
public sealed class UnknownGlobalConstant : DConstant
{
public override bool IsUnknown { get { return true; } }
public override bool IsIdentityDefinite { get { return false; } }
public override bool HasValue { get { return false; } }
public UnknownGlobalConstant(string/*!*/ fullName)
: base(fullName)
{
Debug.Assert(fullName != null);
}
public override string GetFullName()
{
return FullName;
}
internal override PhpTypeCode EmitGet(CodeGenerator/*!*/ codeGenerator, ConstructedType constructedType,
bool runtimeVisibilityCheck, string fallbackName)
{
codeGenerator.EmitGetConstantValueOperator(null, this.FullName, fallbackName);
return PhpTypeCode.Object;
}
}
#endregion
#region KnownConstant
public abstract class KnownConstant : DConstant, IPhpMember
{
public sealed override bool IsUnknown { get { return false; } }
/// <summary>
/// Whether the value of the constant is known and stored in the constant-desc.
/// </summary>
public sealed override bool HasValue { get { return node == null && !ConstantDesc.ValueIsDeferred; } }
/// <summary>
/// Real storage of the constant (a field).
/// </summary>
public FieldInfo RealField { get { return realField; } }
public FieldBuilder RealFieldBuilder { get { return (FieldBuilder)realField; } }
protected FieldInfo realField;
private Func<object>/*!*/GetterStub { get { if (getterStub == null) GenerateGetterStub(); return getterStub; } }
private Func<object>/*!*/getterStub = null;
/// <summary>
/// AST node representing the constant. Used for evaluation only.
/// </summary>
internal AST.ConstantDecl Node { get { return node; } }
private AST.ConstantDecl node;
public abstract Text.Span Span { get; }
public abstract SourceUnit SourceUnit { get; }
internal ExportAttribute ExportInfo { get { return exportInfo; } set { exportInfo = value; } }
internal /* protected */ ExportAttribute exportInfo;
/// <summary>
/// Gets whether the constant is exported.
/// </summary>
internal abstract bool IsExported { get; }
public KnownConstant(DConstantDesc/*!*/ constantDesc)
: base(constantDesc)
{
Debug.Assert(constantDesc != null);
this.node = null;
}
internal void SetValue(object value)
{
this.ConstantDesc.LiteralValue = value;
this.node = null;
}
internal void SetNode(AST.ConstantDecl/*!*/ node)
{
this.ConstantDesc.LiteralValue = null;
this.node = node;
}
private void GenerateGetterStub()
{
Debug.Assert(this.realField != null);
Debug.Assert(this.realField.FieldType == typeof(object));
DynamicMethod stub = new DynamicMethod("<^GetterStub>", this.realField.FieldType, Type.EmptyTypes, true);
ILEmitter il = new ILEmitter(stub);
il.Emit(OpCodes.Ldsfld, this.realField);
il.Emit(OpCodes.Ret);
this.getterStub = (Func<object>)stub.CreateDelegate(typeof(Func<object>));
}
#region Emission
internal override PhpTypeCode EmitGet(CodeGenerator/*!*/ codeGenerator, ConstructedType constructedType,
bool runtimeVisibilityCheck, string fallbackName)
{
ILEmitter il = codeGenerator.IL;
if (HasValue)
{
il.LoadLiteral(Value);
return PhpTypeCodeEnum.FromObject(Value);
}
else
{
Debug.Assert(realField != null);
il.Emit(OpCodes.Ldsfld, DType.MakeConstructed(realField, constructedType));
return PhpTypeCodeEnum.FromType(realField.FieldType);
}
}
#endregion
#region Run-Time Operations
internal object GetValue()
{
Debug.Assert(realField != null);
return GetterStub();
}
#endregion
}
#endregion
#region GlobalConstant
/// <summary>
/// Pure mode global constants, namespace constants, CLR constants, library constants.
/// </summary>
public sealed class GlobalConstant : KnownConstant, IDeclaree
{
#region Statics
public static readonly GlobalConstant Null;
public static readonly GlobalConstant False;
public static readonly GlobalConstant True;
public static readonly GlobalConstant PhpIntSize;
public static readonly GlobalConstant PhpIntMax;
static GlobalConstant()
{
if (UnknownModule.RuntimeModule == null) UnknownModule.RuntimeModule = new UnknownModule();
Null = new GlobalConstant(QualifiedName.Null, Fields.PhpVariable_LiteralNull);
Null.SetValue(null);
False = new GlobalConstant(QualifiedName.False, Fields.PhpVariable_LiteralFalse);
False.SetValue(false);
True = new GlobalConstant(QualifiedName.True, Fields.PhpVariable_LiteralTrue);
True.SetValue(true);
PhpIntSize = new GlobalConstant(new QualifiedName(new Name("PHP_INT_SIZE")), typeof(PhpVariable).GetField("LiteralIntSize"));
PhpIntSize.SetValue(PhpVariable.LiteralIntSize);
PhpIntMax = new GlobalConstant(new QualifiedName(new Name("PHP_INT_MAX")), typeof(int).GetField("MaxValue"));
PhpIntMax.SetValue(int.MaxValue);
}
#endregion
#region Properties
public override bool IsIdentityDefinite
{
get { return declaration == null || !declaration.IsConditional; }
}
public IPhpModuleBuilder DeclaringModuleBuilder { get { return (IPhpModuleBuilder)DeclaringModule; } }
/// <summary>
/// Note: the base name is case-sensitive.
/// </summary>
public QualifiedName QualifiedName { get { return qualifiedName; } }
private readonly QualifiedName qualifiedName;
public Declaration Declaration { get { return declaration; } }
private Declaration declaration;
public VersionInfo Version { get { return version; } set { version = value; } }
private VersionInfo version;
public override Text.Span Span { get { return declaration.Span; } }
public override SourceUnit SourceUnit { get { return declaration.SourceUnit; } }
/// <summary>
/// If constant defined within <script> type, remember its builder to define constant field there.
/// In case of pure or transient module, this is null. If this is null, the constant is declared in as CLR global.
/// </summary>
private TypeBuilder scriptTypeBuilder = null;
/// <summary>
/// Name of the extension where this global constant was defined.
/// </summary>
public string Extension
{
get
{
PhpLibraryModule libraryModule = DeclaringModule as PhpLibraryModule;
if (libraryModule != null)
return libraryModule.GetImplementedExtension(realField.DeclaringType);
else
return null;
}
}
internal override bool IsExported
{
get
{
return exportInfo != null;
}
}
#endregion
#region Construction
/// <summary>
/// Used for constants created by run-time, but with known declaring module
/// </summary>
internal GlobalConstant(DModule/*!*/ declaringModule, QualifiedName qualifiedName, FieldInfo info)
: base(new DConstantDesc(declaringModule, PhpMemberAttributes.None, null))
{
this.realField = info;
this.qualifiedName = qualifiedName;
}
/// <summary>
/// Used for constants created by run-time.
/// </summary>
internal GlobalConstant(QualifiedName qualifiedName, FieldInfo info)
: base(new DConstantDesc(UnknownModule.RuntimeModule, PhpMemberAttributes.None, null))
{
this.realField = info;
this.qualifiedName = qualifiedName;
}
/// <summary>
/// Used by compiler.
/// </summary>
public GlobalConstant(QualifiedName qualifiedName, PhpMemberAttributes memberAttributes,
CompilationSourceUnit/*!*/ sourceUnit, bool isConditional, Scope scope, Text.Span position)
: base(new DConstantDesc(sourceUnit.CompilationUnit.Module, memberAttributes, null))
{
Debug.Assert(sourceUnit != null);
this.qualifiedName = qualifiedName;
this.declaration = new Declaration(sourceUnit, this, false, isConditional, scope, position);
//this.origin = origin;
if (sourceUnit.CompilationUnit is ScriptCompilationUnit) // J: place the constant into <script> type so it can be reflected properly
scriptTypeBuilder = ((ScriptCompilationUnit)sourceUnit.CompilationUnit).ScriptBuilder.ScriptTypeBuilder;
}
#endregion
public override string GetFullName()
{
return qualifiedName.ToString();
}
internal override void ReportCircularDefinition(ErrorSink/*!*/ errors)
{
errors.Add(Errors.CircularConstantDefinitionGlobal, SourceUnit, Span, FullName);
}
public void ReportRedeclaration(ErrorSink/*!*/ errors)
{
errors.Add(FatalErrors.ConstantRedeclared, SourceUnit, Span, FullName);
}
internal void DefineBuilders()
{
if (realField == null)
{
// resolve attributes
FieldAttributes field_attrs = Enums.ToFieldAttributes(memberDesc.MemberAttributes);
field_attrs |= FieldAttributes.Literal;
Debug.Assert((field_attrs & FieldAttributes.Static) != 0);
// convert name to CLR notation:
var clrName = qualifiedName.ToClrNotation(0, 0);
// type
Type type = Types.Object[0];
if (this.HasValue && this.Value != null)
type = this.Value.GetType();
// define public static const field:
if (scriptTypeBuilder != null) // const in SSA or MSA
{
realField = scriptTypeBuilder.DefineField(clrName, type, field_attrs);
}
else // const in Pure or Transient
{
ModuleBuilder module_builder = this.DeclaringModuleBuilder.AssemblyBuilder.RealModuleBuilder;
// represent the class constant as a static initonly field
realField = ReflectionUtils.DefineGlobalField(module_builder, clrName, type, field_attrs);
}
Debug.Assert(realField != null);
// set value
if (this.HasValue)
((FieldBuilder)realField).SetConstant(this.Value);
}
}
internal DConstantDesc Bake()
{
// TODO: rereflection
return this.ConstantDesc;
}
}
#endregion
#region ClassConstant
public sealed class ClassConstant : KnownConstant
{
public override bool IsIdentityDefinite { get { return true; } }
public VariableName Name { get { return name; } }
private readonly VariableName name;
/// <summary>
/// Error reporting.
/// <see cref="ShortPosition.Invalid"/> for reflected PHP methods.
/// </summary>
public override Text.Span Span { get { return span; } }
private readonly Text.Span span;
/// <summary>
/// Error reporting (for partial classes).
/// <B>null</B> for reflected PHP methods.
/// </summary>
public override SourceUnit SourceUnit { get { return sourceUnit; } }
private SourceUnit sourceUnit;
internal override bool IsExported
{
get
{ return exportInfo != null || this.DeclaringPhpType.IsExported; }
}
#region Construction
/// <summary>
/// Used by compiler.
/// </summary>
public ClassConstant(VariableName name, DTypeDesc/*!*/ declaringType, PhpMemberAttributes memberAttributes,
SourceUnit/*!*/ sourceUnit, Text.Span position)
: base(new DConstantDesc(declaringType, memberAttributes, null))
{
Debug.Assert(declaringType != null);
this.name = name;
this.span = position;
this.sourceUnit = sourceUnit;
}
/// <summary>
/// Used by full-reflect (CLR).
/// </summary>
public ClassConstant(VariableName name, DTypeDesc/*!*/ declaringType, PhpMemberAttributes memberAttributes)
: base(new DConstantDesc(declaringType, memberAttributes, null))
{
Debug.Assert(declaringType != null);
this.name = name;
}
/// <summary>
/// Used by full-reflect (PHP).
/// </summary>
public ClassConstant(VariableName name, DConstantDesc/*!*/ constantDesc, FieldInfo/*!*/ fieldInfo)
: base(constantDesc)
{
this.name = name;
this.realField = fieldInfo;
}
#endregion
public override string GetFullName()
{
return name.Value;
}
internal override void ReportCircularDefinition(ErrorSink/*!*/ errors)
{
errors.Add(Errors.CircularConstantDefinitionClass, SourceUnit, Span, DeclaringType.FullName, FullName);
}
/// <summary>
/// Checks whether a specified name is valid constant name.
/// </summary>
/// <param name="name">The constant name.</param>
/// <seealso cref="PhpVariable.IsValidName"/>
public static bool IsValidName(string name)
{
return PhpVariable.IsValidName(name);
}
public void Validate(ErrorSink/*!*/ errors)
{
// nop
}
internal void DefineBuilders()
{
if (realField == null)
{
TypeBuilder type_builder = this.DeclaringPhpType.RealTypeBuilder;
// represent the class constant as a static initonly field
FieldAttributes field_attrs = Enums.ToFieldAttributes(memberDesc.MemberAttributes);
Type field_type = Types.Object[0];
if (this.HasValue)
{
var value = this.Value;
if (value == null || value is int || value is double || value is string || value is long || value is bool)
{
if (value != null)
field_type = value.GetType();
field_attrs |= FieldAttributes.Literal;
}
else
{
field_attrs |= FieldAttributes.InitOnly;
}
}
string name = FullName;
if (IsExported) name += "#";
FieldBuilder fb = type_builder.DefineField(name, field_type, field_attrs);
// [EditorBrowsable(Never)] for user convenience - not on silverlight
#if !SILVERLIGHT
if (IsExported)
fb.SetCustomAttribute(AttributeBuilders.EditorBrowsableNever);
if (!this.HasValue) // constant initialized for every request separatelly (same as static PHP field)
fb.SetCustomAttribute(AttributeBuilders.ThreadStatic);
#endif
realField = fb;
}
}
#region Emission
internal override PhpTypeCode EmitGet(CodeGenerator codeGenerator, ConstructedType constructedType, bool runtimeVisibilityCheck, string fallbackName)
{
if (!HasValue)
{
// __InitializeStaticFields to ensure, this deferred constant has been initialized (same as thread static field):
DeclaringPhpType.EmitThreadStaticInit(codeGenerator, constructedType);
}
return base.EmitGet(codeGenerator, constructedType, runtimeVisibilityCheck, fallbackName);
}
#endregion
}
#endregion
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Xml;
using System.Xml.XPath;
using ODataValidator.Rule.Helper;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
/// <summary>
/// Class of extension rule
/// </summary>
[Export(typeof(ExtensionRule))]
public class MetadataCore4228 : ExtensionRule
{
/// <summary>
/// Gets Category property
/// </summary>
public override string Category
{
get
{
return "core";
}
}
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Metadata.Core.4228";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "The value MUST be a valid value for the UnderlyingType of the enumeration type.";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string SpecificationSection
{
get
{
return "10.2.2";
}
}
/// <summary>
/// Gets location of help information of the rule
/// </summary>
public override string HelpLink
{
get
{
return null;
}
}
/// <summary>
/// Gets the error message for validation failure
/// </summary>
public override string ErrorMessage
{
get
{
return this.Description;
}
}
/// <summary>
/// Gets the requirement level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Must;
}
}
/// <summary>
/// Gets the version.
/// </summary>
public override ODataVersion? Version
{
get
{
return ODataVersion.V4;
}
}
/// <summary>
/// Gets the payload type to which the rule applies.
/// </summary>
public override PayloadType? PayloadType
{
get
{
return RuleEngine.PayloadType.Metadata;
}
}
/// <summary>
/// Gets the flag whether the rule requires metadata document
/// </summary>
public override bool? RequireMetadata
{
get
{
return true;
}
}
/// <summary>
/// Gets the offline context to which the rule applies
/// </summary>
public override bool? IsOfflineContext
{
get
{
return true;
}
}
/// <summary>
/// Gets the payload format to which the rule applies.
/// </summary>
public override PayloadFormat? PayloadFormat
{
get
{
return RuleEngine.PayloadFormat.Xml;
}
}
/// <summary>
/// Verify Metadata.Core.4228
/// </summary>
/// <param name="context">Service context</param>
/// <param name="info">out parameter to return violation information when rule fail</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = null;
info = null;
// Load MetadataDocument into XMLDOM
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(context.MetadataDocument);
string xpath = "//*[local-name()='EnumType']";
XmlNodeList enumTypeNodeList = xmlDoc.SelectNodes(xpath);
foreach (XmlNode enumType in enumTypeNodeList)
{
string underlyingType = string.Empty;
if (enumType.Attributes["UnderlyingType"] != null)
{
underlyingType = enumType.Attributes["UnderlyingType"].Value;
}
else
{
underlyingType = "Edm.Int32";
}
foreach (XmlNode member in enumType.ChildNodes)
{
if (!member.Name.Equals("Member"))
{
continue;
}
else
{
if (member.Attributes["Value"] != null)
{
IEdmType edmType = EdmTypeManager.GetEdmType(underlyingType);
if (edmType.IsGoodWith(member.Attributes["Value"].Value))
{
passed = true;
}
else
{
passed = false;
info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
break;
}
}
}
}
if (passed == false)
{
break;
}
}
return passed;
}
}
}
| |
// 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;
namespace System.Xml.Xsl.Qil
{
/// <summary>
/// Factory methods for constructing QilExpression nodes.
/// </summary>
/// <remarks>
/// See <see href="http://dynamo/qil/qil.xml">the QIL functional specification</see> for documentation.
/// </remarks>
internal sealed class QilFactory
{
private readonly QilTypeChecker _typeCheck;
public QilFactory()
{
_typeCheck = new QilTypeChecker();
}
public QilTypeChecker TypeChecker
{
get { return _typeCheck; }
}
//-----------------------------------------------
// Convenience methods
//-----------------------------------------------
public QilExpression QilExpression(QilNode root, QilFactory factory)
{
QilExpression n = new QilExpression(QilNodeType.QilExpression, root, factory);
n.XmlType = _typeCheck.CheckQilExpression(n);
TraceNode(n);
return n;
}
public QilList ActualParameterList(IList<QilNode> values)
{
QilList seq = ActualParameterList();
seq.Add(values);
return seq;
}
public QilList FormalParameterList(IList<QilNode> values)
{
QilList seq = FormalParameterList();
seq.Add(values);
return seq;
}
public QilList BranchList(IList<QilNode> values)
{
QilList seq = BranchList();
seq.Add(values);
return seq;
}
public QilList Sequence(IList<QilNode> values)
{
QilList seq = Sequence();
seq.Add(values);
return seq;
}
public QilParameter Parameter(XmlQueryType xmlType)
{
return Parameter(null, null, xmlType);
}
public QilStrConcat StrConcat(QilNode values)
{
return StrConcat(LiteralString(""), values);
}
public QilName LiteralQName(string local)
{
return LiteralQName(local, string.Empty, string.Empty);
}
public QilTargetType TypeAssert(QilNode expr, XmlQueryType xmlType)
{
return TypeAssert(expr, (QilNode)LiteralType(xmlType));
}
public QilTargetType IsType(QilNode expr, XmlQueryType xmlType)
{
return IsType(expr, (QilNode)LiteralType(xmlType));
}
public QilTargetType XsltConvert(QilNode expr, XmlQueryType xmlType)
{
return XsltConvert(expr, (QilNode)LiteralType(xmlType));
}
public QilFunction Function(QilNode arguments, QilNode sideEffects, XmlQueryType xmlType)
{
return Function(arguments, Unknown(xmlType), sideEffects, xmlType);
}
#region AUTOGENERATED
#region meta
public QilList FunctionList()
{
QilList n = new QilList(QilNodeType.FunctionList);
n.XmlType = _typeCheck.CheckFunctionList(n);
TraceNode(n);
return n;
}
public QilList GlobalVariableList()
{
QilList n = new QilList(QilNodeType.GlobalVariableList);
n.XmlType = _typeCheck.CheckGlobalVariableList(n);
TraceNode(n);
return n;
}
public QilList GlobalParameterList()
{
QilList n = new QilList(QilNodeType.GlobalParameterList);
n.XmlType = _typeCheck.CheckGlobalParameterList(n);
TraceNode(n);
return n;
}
public QilList ActualParameterList()
{
QilList n = new QilList(QilNodeType.ActualParameterList);
n.XmlType = _typeCheck.CheckActualParameterList(n);
TraceNode(n);
return n;
}
public QilList FormalParameterList()
{
QilList n = new QilList(QilNodeType.FormalParameterList);
n.XmlType = _typeCheck.CheckFormalParameterList(n);
TraceNode(n);
return n;
}
public QilList SortKeyList()
{
QilList n = new QilList(QilNodeType.SortKeyList);
n.XmlType = _typeCheck.CheckSortKeyList(n);
TraceNode(n);
return n;
}
public QilList BranchList()
{
QilList n = new QilList(QilNodeType.BranchList);
n.XmlType = _typeCheck.CheckBranchList(n);
TraceNode(n);
return n;
}
public QilUnary OptimizeBarrier(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.OptimizeBarrier, child);
n.XmlType = _typeCheck.CheckOptimizeBarrier(n);
TraceNode(n);
return n;
}
public QilNode Unknown(XmlQueryType xmlType)
{
QilNode n = new QilNode(QilNodeType.Unknown, xmlType);
n.XmlType = _typeCheck.CheckUnknown(n);
TraceNode(n);
return n;
}
#endregion // meta
#region specials
//-----------------------------------------------
// specials
//-----------------------------------------------
public QilDataSource DataSource(QilNode name, QilNode baseUri)
{
QilDataSource n = new QilDataSource(QilNodeType.DataSource, name, baseUri);
n.XmlType = _typeCheck.CheckDataSource(n);
TraceNode(n);
return n;
}
public QilUnary Nop(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Nop, child);
n.XmlType = _typeCheck.CheckNop(n);
TraceNode(n);
return n;
}
public QilUnary Error(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Error, child);
n.XmlType = _typeCheck.CheckError(n);
TraceNode(n);
return n;
}
public QilUnary Warning(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Warning, child);
n.XmlType = _typeCheck.CheckWarning(n);
TraceNode(n);
return n;
}
#endregion // specials
#region variables
//-----------------------------------------------
// variables
//-----------------------------------------------
public QilIterator For(QilNode binding)
{
QilIterator n = new QilIterator(QilNodeType.For, binding);
n.XmlType = _typeCheck.CheckFor(n);
TraceNode(n);
return n;
}
public QilIterator Let(QilNode binding)
{
QilIterator n = new QilIterator(QilNodeType.Let, binding);
n.XmlType = _typeCheck.CheckLet(n);
TraceNode(n);
return n;
}
public QilParameter Parameter(QilNode defaultValue, QilNode name, XmlQueryType xmlType)
{
QilParameter n = new QilParameter(QilNodeType.Parameter, defaultValue, name, xmlType);
n.XmlType = _typeCheck.CheckParameter(n);
TraceNode(n);
return n;
}
public QilUnary PositionOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.PositionOf, child);
n.XmlType = _typeCheck.CheckPositionOf(n);
TraceNode(n);
return n;
}
#endregion // variables
#region literals
//-----------------------------------------------
// literals
//-----------------------------------------------
public QilNode True()
{
QilNode n = new QilNode(QilNodeType.True);
n.XmlType = _typeCheck.CheckTrue(n);
TraceNode(n);
return n;
}
public QilNode False()
{
QilNode n = new QilNode(QilNodeType.False);
n.XmlType = _typeCheck.CheckFalse(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralString(string value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralString, value);
n.XmlType = _typeCheck.CheckLiteralString(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralInt32(int value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralInt32, value);
n.XmlType = _typeCheck.CheckLiteralInt32(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralInt64(long value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralInt64, value);
n.XmlType = _typeCheck.CheckLiteralInt64(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralDouble(double value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralDouble, value);
n.XmlType = _typeCheck.CheckLiteralDouble(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralDecimal(decimal value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralDecimal, value);
n.XmlType = _typeCheck.CheckLiteralDecimal(n);
TraceNode(n);
return n;
}
public QilName LiteralQName(string localName, string namespaceUri, string prefix)
{
QilName n = new QilName(QilNodeType.LiteralQName, localName, namespaceUri, prefix);
n.XmlType = _typeCheck.CheckLiteralQName(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralType(XmlQueryType value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralType, value);
n.XmlType = _typeCheck.CheckLiteralType(n);
TraceNode(n);
return n;
}
public QilLiteral LiteralObject(object value)
{
QilLiteral n = new QilLiteral(QilNodeType.LiteralObject, value);
n.XmlType = _typeCheck.CheckLiteralObject(n);
TraceNode(n);
return n;
}
#endregion // literals
#region boolean operators
//-----------------------------------------------
// boolean operators
//-----------------------------------------------
public QilBinary And(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.And, left, right);
n.XmlType = _typeCheck.CheckAnd(n);
TraceNode(n);
return n;
}
public QilBinary Or(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Or, left, right);
n.XmlType = _typeCheck.CheckOr(n);
TraceNode(n);
return n;
}
public QilUnary Not(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Not, child);
n.XmlType = _typeCheck.CheckNot(n);
TraceNode(n);
return n;
}
#endregion // boolean operators
#region choice
//-----------------------------------------------
// choice
//-----------------------------------------------
public QilTernary Conditional(QilNode left, QilNode center, QilNode right)
{
QilTernary n = new QilTernary(QilNodeType.Conditional, left, center, right);
n.XmlType = _typeCheck.CheckConditional(n);
TraceNode(n);
return n;
}
public QilChoice Choice(QilNode expression, QilNode branches)
{
QilChoice n = new QilChoice(QilNodeType.Choice, expression, branches);
n.XmlType = _typeCheck.CheckChoice(n);
TraceNode(n);
return n;
}
#endregion // choice
#region collection operators
//-----------------------------------------------
// collection operators
//-----------------------------------------------
public QilUnary Length(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Length, child);
n.XmlType = _typeCheck.CheckLength(n);
TraceNode(n);
return n;
}
public QilList Sequence()
{
QilList n = new QilList(QilNodeType.Sequence);
n.XmlType = _typeCheck.CheckSequence(n);
TraceNode(n);
return n;
}
public QilBinary Union(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Union, left, right);
n.XmlType = _typeCheck.CheckUnion(n);
TraceNode(n);
return n;
}
public QilBinary Intersection(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Intersection, left, right);
n.XmlType = _typeCheck.CheckIntersection(n);
TraceNode(n);
return n;
}
public QilBinary Difference(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Difference, left, right);
n.XmlType = _typeCheck.CheckDifference(n);
TraceNode(n);
return n;
}
public QilUnary Sum(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Sum, child);
n.XmlType = _typeCheck.CheckSum(n);
TraceNode(n);
return n;
}
#endregion // collection operators
#region arithmetic operators
//-----------------------------------------------
// arithmetic operators
//-----------------------------------------------
public QilUnary Negate(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Negate, child);
n.XmlType = _typeCheck.CheckNegate(n);
TraceNode(n);
return n;
}
public QilBinary Add(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Add, left, right);
n.XmlType = _typeCheck.CheckAdd(n);
TraceNode(n);
return n;
}
public QilBinary Subtract(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Subtract, left, right);
n.XmlType = _typeCheck.CheckSubtract(n);
TraceNode(n);
return n;
}
public QilBinary Multiply(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Multiply, left, right);
n.XmlType = _typeCheck.CheckMultiply(n);
TraceNode(n);
return n;
}
public QilBinary Divide(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Divide, left, right);
n.XmlType = _typeCheck.CheckDivide(n);
TraceNode(n);
return n;
}
public QilBinary Modulo(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Modulo, left, right);
n.XmlType = _typeCheck.CheckModulo(n);
TraceNode(n);
return n;
}
#endregion // arithmetic operators
#region string operators
//-----------------------------------------------
// string operators
//-----------------------------------------------
public QilUnary StrLength(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.StrLength, child);
n.XmlType = _typeCheck.CheckStrLength(n);
TraceNode(n);
return n;
}
public QilStrConcat StrConcat(QilNode delimiter, QilNode values)
{
QilStrConcat n = new QilStrConcat(QilNodeType.StrConcat, delimiter, values);
n.XmlType = _typeCheck.CheckStrConcat(n);
TraceNode(n);
return n;
}
public QilBinary StrParseQName(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.StrParseQName, left, right);
n.XmlType = _typeCheck.CheckStrParseQName(n);
TraceNode(n);
return n;
}
#endregion // string operators
#region value comparison operators
//-----------------------------------------------
// value comparison operators
//-----------------------------------------------
public QilBinary Ne(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Ne, left, right);
n.XmlType = _typeCheck.CheckNe(n);
TraceNode(n);
return n;
}
public QilBinary Eq(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Eq, left, right);
n.XmlType = _typeCheck.CheckEq(n);
TraceNode(n);
return n;
}
public QilBinary Gt(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Gt, left, right);
n.XmlType = _typeCheck.CheckGt(n);
TraceNode(n);
return n;
}
public QilBinary Ge(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Ge, left, right);
n.XmlType = _typeCheck.CheckGe(n);
TraceNode(n);
return n;
}
public QilBinary Lt(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Lt, left, right);
n.XmlType = _typeCheck.CheckLt(n);
TraceNode(n);
return n;
}
public QilBinary Le(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Le, left, right);
n.XmlType = _typeCheck.CheckLe(n);
TraceNode(n);
return n;
}
#endregion // value comparison operators
#region node comparison operators
//-----------------------------------------------
// node comparison operators
//-----------------------------------------------
public QilBinary Is(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Is, left, right);
n.XmlType = _typeCheck.CheckIs(n);
TraceNode(n);
return n;
}
public QilBinary Before(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Before, left, right);
n.XmlType = _typeCheck.CheckBefore(n);
TraceNode(n);
return n;
}
#endregion // node comparison operators
#region loops
//-----------------------------------------------
// loops
//-----------------------------------------------
public QilLoop Loop(QilNode variable, QilNode body)
{
QilLoop n = new QilLoop(QilNodeType.Loop, variable, body);
n.XmlType = _typeCheck.CheckLoop(n);
TraceNode(n);
return n;
}
public QilLoop Filter(QilNode variable, QilNode body)
{
QilLoop n = new QilLoop(QilNodeType.Filter, variable, body);
n.XmlType = _typeCheck.CheckFilter(n);
TraceNode(n);
return n;
}
#endregion // loops
#region sorting
//-----------------------------------------------
// sorting
//-----------------------------------------------
public QilLoop Sort(QilNode variable, QilNode body)
{
QilLoop n = new QilLoop(QilNodeType.Sort, variable, body);
n.XmlType = _typeCheck.CheckSort(n);
TraceNode(n);
return n;
}
public QilSortKey SortKey(QilNode key, QilNode collation)
{
QilSortKey n = new QilSortKey(QilNodeType.SortKey, key, collation);
n.XmlType = _typeCheck.CheckSortKey(n);
TraceNode(n);
return n;
}
public QilUnary DocOrderDistinct(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.DocOrderDistinct, child);
n.XmlType = _typeCheck.CheckDocOrderDistinct(n);
TraceNode(n);
return n;
}
#endregion // sorting
#region function definition and invocation
//-----------------------------------------------
// function definition and invocation
//-----------------------------------------------
public QilFunction Function(QilNode arguments, QilNode definition, QilNode sideEffects, XmlQueryType xmlType)
{
QilFunction n = new QilFunction(QilNodeType.Function, arguments, definition, sideEffects, xmlType);
n.XmlType = _typeCheck.CheckFunction(n);
TraceNode(n);
return n;
}
public QilInvoke Invoke(QilNode function, QilNode arguments)
{
QilInvoke n = new QilInvoke(QilNodeType.Invoke, function, arguments);
n.XmlType = _typeCheck.CheckInvoke(n);
TraceNode(n);
return n;
}
#endregion // function definition and invocation
#region XML navigation
//-----------------------------------------------
// XML navigation
//-----------------------------------------------
public QilUnary Content(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Content, child);
n.XmlType = _typeCheck.CheckContent(n);
TraceNode(n);
return n;
}
public QilBinary Attribute(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Attribute, left, right);
n.XmlType = _typeCheck.CheckAttribute(n);
TraceNode(n);
return n;
}
public QilUnary Parent(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Parent, child);
n.XmlType = _typeCheck.CheckParent(n);
TraceNode(n);
return n;
}
public QilUnary Root(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Root, child);
n.XmlType = _typeCheck.CheckRoot(n);
TraceNode(n);
return n;
}
public QilNode XmlContext()
{
QilNode n = new QilNode(QilNodeType.XmlContext);
n.XmlType = _typeCheck.CheckXmlContext(n);
TraceNode(n);
return n;
}
public QilUnary Descendant(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Descendant, child);
n.XmlType = _typeCheck.CheckDescendant(n);
TraceNode(n);
return n;
}
public QilUnary DescendantOrSelf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.DescendantOrSelf, child);
n.XmlType = _typeCheck.CheckDescendantOrSelf(n);
TraceNode(n);
return n;
}
public QilUnary Ancestor(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Ancestor, child);
n.XmlType = _typeCheck.CheckAncestor(n);
TraceNode(n);
return n;
}
public QilUnary AncestorOrSelf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.AncestorOrSelf, child);
n.XmlType = _typeCheck.CheckAncestorOrSelf(n);
TraceNode(n);
return n;
}
public QilUnary Preceding(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.Preceding, child);
n.XmlType = _typeCheck.CheckPreceding(n);
TraceNode(n);
return n;
}
public QilUnary FollowingSibling(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.FollowingSibling, child);
n.XmlType = _typeCheck.CheckFollowingSibling(n);
TraceNode(n);
return n;
}
public QilUnary PrecedingSibling(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.PrecedingSibling, child);
n.XmlType = _typeCheck.CheckPrecedingSibling(n);
TraceNode(n);
return n;
}
public QilBinary NodeRange(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.NodeRange, left, right);
n.XmlType = _typeCheck.CheckNodeRange(n);
TraceNode(n);
return n;
}
public QilBinary Deref(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.Deref, left, right);
n.XmlType = _typeCheck.CheckDeref(n);
TraceNode(n);
return n;
}
#endregion // XML navigation
#region XML construction
//-----------------------------------------------
// XML construction
//-----------------------------------------------
public QilBinary ElementCtor(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.ElementCtor, left, right);
n.XmlType = _typeCheck.CheckElementCtor(n);
TraceNode(n);
return n;
}
public QilBinary AttributeCtor(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.AttributeCtor, left, right);
n.XmlType = _typeCheck.CheckAttributeCtor(n);
TraceNode(n);
return n;
}
public QilUnary CommentCtor(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.CommentCtor, child);
n.XmlType = _typeCheck.CheckCommentCtor(n);
TraceNode(n);
return n;
}
public QilBinary PICtor(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.PICtor, left, right);
n.XmlType = _typeCheck.CheckPICtor(n);
TraceNode(n);
return n;
}
public QilUnary TextCtor(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.TextCtor, child);
n.XmlType = _typeCheck.CheckTextCtor(n);
TraceNode(n);
return n;
}
public QilUnary RawTextCtor(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.RawTextCtor, child);
n.XmlType = _typeCheck.CheckRawTextCtor(n);
TraceNode(n);
return n;
}
public QilUnary DocumentCtor(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.DocumentCtor, child);
n.XmlType = _typeCheck.CheckDocumentCtor(n);
TraceNode(n);
return n;
}
public QilBinary NamespaceDecl(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.NamespaceDecl, left, right);
n.XmlType = _typeCheck.CheckNamespaceDecl(n);
TraceNode(n);
return n;
}
public QilBinary RtfCtor(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.RtfCtor, left, right);
n.XmlType = _typeCheck.CheckRtfCtor(n);
TraceNode(n);
return n;
}
#endregion // XML construction
#region Node properties
//-----------------------------------------------
// Node properties
//-----------------------------------------------
public QilUnary NameOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.NameOf, child);
n.XmlType = _typeCheck.CheckNameOf(n);
TraceNode(n);
return n;
}
public QilUnary LocalNameOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.LocalNameOf, child);
n.XmlType = _typeCheck.CheckLocalNameOf(n);
TraceNode(n);
return n;
}
public QilUnary NamespaceUriOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.NamespaceUriOf, child);
n.XmlType = _typeCheck.CheckNamespaceUriOf(n);
TraceNode(n);
return n;
}
public QilUnary PrefixOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.PrefixOf, child);
n.XmlType = _typeCheck.CheckPrefixOf(n);
TraceNode(n);
return n;
}
#endregion // Node properties
#region Type operators
//-----------------------------------------------
// Type operators
//-----------------------------------------------
public QilTargetType TypeAssert(QilNode source, QilNode targetType)
{
QilTargetType n = new QilTargetType(QilNodeType.TypeAssert, source, targetType);
n.XmlType = _typeCheck.CheckTypeAssert(n);
TraceNode(n);
return n;
}
public QilTargetType IsType(QilNode source, QilNode targetType)
{
QilTargetType n = new QilTargetType(QilNodeType.IsType, source, targetType);
n.XmlType = _typeCheck.CheckIsType(n);
TraceNode(n);
return n;
}
public QilUnary IsEmpty(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.IsEmpty, child);
n.XmlType = _typeCheck.CheckIsEmpty(n);
TraceNode(n);
return n;
}
#endregion // Type operators
#region XPath operators
//-----------------------------------------------
// XPath operators
//-----------------------------------------------
public QilUnary XPathNodeValue(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XPathNodeValue, child);
n.XmlType = _typeCheck.CheckXPathNodeValue(n);
TraceNode(n);
return n;
}
public QilUnary XPathFollowing(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XPathFollowing, child);
n.XmlType = _typeCheck.CheckXPathFollowing(n);
TraceNode(n);
return n;
}
public QilUnary XPathPreceding(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XPathPreceding, child);
n.XmlType = _typeCheck.CheckXPathPreceding(n);
TraceNode(n);
return n;
}
public QilUnary XPathNamespace(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XPathNamespace, child);
n.XmlType = _typeCheck.CheckXPathNamespace(n);
TraceNode(n);
return n;
}
#endregion // XPath operators
#region XSLT
//-----------------------------------------------
// XSLT
//-----------------------------------------------
public QilUnary XsltGenerateId(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XsltGenerateId, child);
n.XmlType = _typeCheck.CheckXsltGenerateId(n);
TraceNode(n);
return n;
}
public QilInvokeLateBound XsltInvokeLateBound(QilNode name, QilNode arguments)
{
QilInvokeLateBound n = new QilInvokeLateBound(QilNodeType.XsltInvokeLateBound, name, arguments);
n.XmlType = _typeCheck.CheckXsltInvokeLateBound(n);
TraceNode(n);
return n;
}
public QilInvokeEarlyBound XsltInvokeEarlyBound(QilNode name, QilNode clrMethod, QilNode arguments, XmlQueryType xmlType)
{
QilInvokeEarlyBound n = new QilInvokeEarlyBound(QilNodeType.XsltInvokeEarlyBound, name, clrMethod, arguments, xmlType);
n.XmlType = _typeCheck.CheckXsltInvokeEarlyBound(n);
TraceNode(n);
return n;
}
public QilBinary XsltCopy(QilNode left, QilNode right)
{
QilBinary n = new QilBinary(QilNodeType.XsltCopy, left, right);
n.XmlType = _typeCheck.CheckXsltCopy(n);
TraceNode(n);
return n;
}
public QilUnary XsltCopyOf(QilNode child)
{
QilUnary n = new QilUnary(QilNodeType.XsltCopyOf, child);
n.XmlType = _typeCheck.CheckXsltCopyOf(n);
TraceNode(n);
return n;
}
public QilTargetType XsltConvert(QilNode source, QilNode targetType)
{
QilTargetType n = new QilTargetType(QilNodeType.XsltConvert, source, targetType);
n.XmlType = _typeCheck.CheckXsltConvert(n);
TraceNode(n);
return n;
}
#endregion // XSLT
#endregion
#region Diagnostic Support
[System.Diagnostics.Conditional("QIL_TRACE_NODE_CREATION")]
public void TraceNode(QilNode n)
{
#if QIL_TRACE_NODE_CREATION
this.diag.AddNode(n);
#endif
}
#endregion
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Data;
namespace DotSpatial.Data
{
/// <summary>
/// This represents the column information for one column of a shapefile.
/// This specifies precision as well as the typical column information.
/// </summary>
public class Field : DataColumn
{
#region Properties
/// <summary>
/// Initializes a new instance of the <see cref="Field"/> class that is empty.
/// This is needed for datatable copy and clone methods.
/// </summary>
public Field()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Field"/> class.
/// Creates a new default field given the specified DataColumn. Numeric types
/// default to a size of 255, but will be shortened during the save opperation.
/// The default decimal count for double and long is 0, for Currency is 2, for float is
/// 3, and for double is 8. These can be changed by changing the DecimalCount property.
/// </summary>
/// <param name="inColumn">A System.Data.DataColumn to create a Field from</param>
public Field(DataColumn inColumn)
: base(inColumn.ColumnName, inColumn.DataType, inColumn.Expression, inColumn.ColumnMapping)
{
SetupDecimalCount();
if (inColumn.DataType == typeof(string))
{
Length = inColumn.MaxLength <= 254 ? (byte)inColumn.MaxLength : (byte)254;
}
else if (inColumn.DataType == typeof(DateTime))
{
Length = 8;
}
else if (inColumn.DataType == typeof(bool))
{
Length = 1;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Field"/> class, as type string, using the specified column name.
/// </summary>
/// <param name="inColumnName">The string name of the column.</param>
public Field(string inColumnName)
: base(inColumnName)
{
// can't setup decimal count without a data type
}
/// <summary>
/// Initializes a new instance of the <see cref="Field"/> class with a specific name for a specified data type.
/// </summary>
/// <param name="inColumnName">The string name of the column.</param>
/// <param name="inDataType">The System.Type describing the datatype of the field</param>
public Field(string inColumnName, Type inDataType)
: base(inColumnName, inDataType)
{
SetupDecimalCount();
}
/// <summary>
/// Initializes a new instance of the <see cref="Field"/> class with a specific name and using a simplified enumeration of possible types.
/// </summary>
/// <param name="inColumnName">The string name of the column.</param>
/// <param name="type">The type enumeration that clarifies which basic data type to use.</param>
public Field(string inColumnName, FieldDataType type)
: base(inColumnName)
{
if (type == FieldDataType.Double) DataType = typeof(double);
if (type == FieldDataType.Integer) DataType = typeof(int);
if (type == FieldDataType.String) DataType = typeof(string);
}
/*
* Field Types Specified by the dBASE Format Specifications
*
* http://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm
*
* Symbol | Data Type | Description
* -------+--------------+-------------------------------------------------------------------------------------
* B | Binary | 10 digits representing a .DBT block number. The number is stored as a string, right justified and padded with blanks.
* C | Character | All OEM code page characters - padded with blanks to the width of the field.
* D | Date | 8 bytes - date stored as a string in the format YYYYMMDD.
* N | Numeric | Number stored as a string, right justified, and padded with blanks to the width of the field.
* L | Logical | 1 byte - initialized to 0x20 (space) otherwise T or F.
* M | Memo | 10 digits (bytes) representing a .DBT block number. The number is stored as a string, right justified and padded with blanks.
* @ | Timestamp | 8 bytes - two longs, first for date, second for time. The date is the number of days since 01/01/4713 BC. Time is hours * 3600000L + minutes * 60000L + Seconds * 1000L
* I | Long | 4 bytes. Leftmost bit used to indicate sign, 0 negative.
* + |Autoincrement | Same as a Long
* F | Float | Number stored as a string, right justified, and padded with blanks to the width of the field.
* O | Double | 8 bytes - no conversions, stored as a double.
* G | OLE | 10 digits (bytes) representing a .DBT block number. The number is stored as a string, right justified and padded with blanks.
*/
/// <summary>
/// Initializes a new instance of the <see cref="Field"/> class.
/// </summary>
/// <param name="columnName">The string name of the column.</param>
/// <param name="typeCode">A code specified by the dBASE Format Specifications that indicates what type should be used.</param>
/// <param name="length">The character length of the field.</param>
/// <param name="decimalCount">Represents the number of decimals to preserve after a 0.</param>
public Field(string columnName, char typeCode, byte length, byte decimalCount)
: base(columnName)
{
Length = length;
ColumnName = columnName;
DecimalCount = decimalCount;
// Date or Timestamp
if (typeCode == 'D' || typeCode == '@')
{
// date
DataType = typeof(DateTime);
return;
}
if (typeCode == 'L')
{
DataType = typeof(bool);
return;
}
// Long or AutoIncrement
if (typeCode == 'I' || typeCode == '+')
{
DataType = typeof(int);
return;
}
if (typeCode == 'O')
{
DataType = typeof(double);
return;
}
if (typeCode == 'N' || typeCode == 'B' || typeCode == 'M' || typeCode == 'F' || typeCode == 'G')
{
// The strategy here is to assign the smallest type that we KNOW will be large enough
// to hold any value with the length (in digits) and characters.
// even though double can hold as high a value as a "Number" can go, it can't
// preserve the extraordinary 255 digit precision that a Number has. The strategy
// is to assess the length in characters and assign a numeric type where no
// value may exist outside the range. (They can always change the datatype later.)
// The basic encoding we are using here
if (decimalCount == 0)
{
if (length < 3)
{
// 0 to 255
DataType = typeof(byte);
return;
}
if (length < 5)
{
// -32768 to 32767
DataType = typeof(short); // Int16
return;
}
if (length < 10)
{
// -2147483648 to 2147483647
DataType = typeof(int); // Int32
return;
}
if (length < 19)
{
// -9223372036854775808 to -9223372036854775807
DataType = typeof(long); // Int64
return;
}
}
if (decimalCount > 15)
{
// we know this has too many significant digits to fit in a double:
// a double can hold 15-16 significant digits: https://msdn.microsoft.com/en-us/library/678hzkk9.aspx
DataType = typeof(string);
MaxLength = length;
return;
}
// Singles -3.402823E+38 to 3.402823E+38
// Doubles -1.79769313486232E+308 to 1.79769313486232E+308
// Decimals -79228162514264337593543950335 to 79228162514264337593543950335
// Doubles have the range to handle any number with the 255 character size,
// but won't preserve the precision that is possible. It is still
// preferable to have a numeric type in 99% of cases, and double is the easiest.
DataType = typeof(double);
return;
}
// Type code is either C or not recognized, in which case we will just end up with a string
// representation of whatever the characters are.
DataType = typeof(string);
MaxLength = length;
}
/// <summary>
/// Gets the single character dBase code. Only some of these are supported with Esri.
/// C - Character (Chars, Strings, objects - as ToString(), and structs - as )
/// D - Date (DateTime)
/// T - Time (DateTime)
/// N - Number (Short, Integer, Long, Float, Double, byte)
/// L - Logic (True-False, Yes-No)
/// F - Float
/// B - Double
/// </summary>
public char TypeCharacter
{
get
{
if (DataType == typeof(bool)) return 'L';
if (DataType == typeof(DateTime)) return 'D';
// We are using numeric in most cases here, because that is the format most compatible with other
// Applications
if (DataType == typeof(float)) return 'N';
if (DataType == typeof(double)) return 'N';
if (DataType == typeof(decimal)) return 'N';
if (DataType == typeof(byte)) return 'N';
if (DataType == typeof(short)) return 'N';
if (DataType == typeof(int)) return 'N';
if (DataType == typeof(long)) return 'N';
// The default is to store it as a string type
return 'C';
}
}
/// <summary>
/// Gets or sets the number of places to keep after the 0 in number formats.
/// As far as dbf fields are concerned, all numeric datatypes use the same database number format.
/// </summary>
public byte DecimalCount { get; set; }
/// <summary>
/// Gets or sets the length of the field in bytes.
/// </summary>
public byte Length { get; set; }
/// <summary>
/// Gets or sets the offset of the field on a row in the file
/// </summary>
public int DataAddress { get; set; }
/// <summary>
/// Gets or sets the Number Converter associated with this field.
/// </summary>
public NumberConverter NumberConverter { get; set; }
/// <summary>
/// Internal method that decides an appropriate decimal count, given a data column.
/// </summary>
private void SetupDecimalCount()
{
// Going this way, we want a large enough decimal count to hold any of the possible numeric values.
// We will try to make the length large enough to hold any values, but some doubles simply will be
// too large to be stored in this format, so we will throw exceptions if that happens later.
// These sizes represent the "maximized" length and decimal counts that will be shrunk in order
// to fit the data before saving.
if (DataType == typeof(float))
{
//// _decimalCount = (byte)40; // Singles -3.402823E+38 to 3.402823E+38
//// _length = (byte)40;
Length = 18;
DecimalCount = 6;
return;
}
if (DataType == typeof(double))
{
//// _decimalCount = (byte)255; // Doubles -1.79769313486232E+308 to 1.79769313486232E+308
//// _length = (byte)255;
Length = 18;
DecimalCount = 9;
return;
}
if (DataType == typeof(decimal))
{
Length = 18;
DecimalCount = 9; // Decimals -79228162514264337593543950335 to 79228162514264337593543950335
return;
}
if (DataType == typeof(byte))
{
// 0 to 255
DecimalCount = 0;
Length = 3;
return;
}
if (DataType == typeof(short))
{
// -32768 to 32767
Length = 6;
DecimalCount = 0;
return;
}
if (DataType == typeof(int))
{
// -2147483648 to 2147483647
Length = 11;
DecimalCount = 0;
return;
}
if (DataType == typeof(long))
{
// -9223372036854775808 to -9223372036854775807
Length = 20;
DecimalCount = 0;
}
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Microsoft.Azure.Management.Redis;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
namespace Microsoft.Azure.Management.Redis
{
/// <summary>
/// .Net client wrapper for the REST API for Azure Redis Cache Management
/// Service
/// </summary>
public partial class RedisManagementClient : ServiceClient<RedisManagementClient>, IRedisManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IRedisOperations _redis;
/// <summary>
/// Operations for managing the redis cache.
/// </summary>
public virtual IRedisOperations Redis
{
get { return this._redis; }
}
/// <summary>
/// Initializes a new instance of the RedisManagementClient class.
/// </summary>
private RedisManagementClient()
: base()
{
this._redis = new RedisOperations(this);
this._apiVersion = "2014-04-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the RedisManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public RedisManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the RedisManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public RedisManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the RedisManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private RedisManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._redis = new RedisOperations(this);
this._apiVersion = "2014-04-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the RedisManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public RedisManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the RedisManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public RedisManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// RedisManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of RedisManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<RedisManagementClient> client)
{
base.Clone(client);
if (client is RedisManagementClient)
{
RedisManagementClient clonedClient = ((RedisManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
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.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using fyiReporting.RDL;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
namespace fyiReporting.RDL
{
///<summary>
/// Renders a report to PDF. This is a page oriented formatting renderer.
///</summary>
internal class RenderPdf: IPresent
{
Report r; // report
Stream tw; // where the output is going
PdfAnchor anchor; // anchor tieing together all pdf objects
PdfCatalog catalog;
PdfPageTree pageTree;
PdfInfo info;
PdfFonts fonts;
PdfPattern patterns;
PdfImages images;
PdfOutline outline; // holds the bookmarks (if any)
PdfUtility pdfUtility;
int filesize;
PdfPage page;
PdfContent content;
PdfElements elements;
static readonly char[] lineBreak = new char[] {'\n'};
static readonly char[] wordBreak = new char[] {' '};
// static readonly int MEASUREMAX = int.MaxValue; // .Net 2 doesn't seem to have a limit; 1.1 limit was 32
static readonly int MEASUREMAX = 32; // guess I'm wrong -- .Net 2 doesn't seem to have a limit; 1.1 limit was 32
public RenderPdf(Report rep, IStreamGen sg)
{
r = rep;
tw = sg.GetStream();
}
public Report Report()
{
return r;
}
public bool IsPagingNeeded()
{
return true;
}
public void Start()
{
// Create the anchor for all pdf objects
CompressionConfig cc = RdlEngineConfig.GetCompression();
anchor = new PdfAnchor(cc != null);
//Create a PdfCatalog
string lang;
if (r.ReportDefinition.Language != null)
lang = r.ReportDefinition.Language.EvaluateString(this.r, null);
else
lang = null;
catalog= new PdfCatalog(anchor, lang);
//Create a Page Tree Dictionary
pageTree= new PdfPageTree(anchor);
//Create a Font Dictionary
fonts = new PdfFonts(anchor);
//Create a Pattern Dictionary
patterns = new PdfPattern(anchor);
//Create an Image Dictionary
images = new PdfImages(anchor);
//Create an Outline Dictionary
outline = new PdfOutline(anchor);
//Create the info Dictionary
info=new PdfInfo(anchor);
//Set the info Dictionary.
info.SetInfo(r.Name,r.Author,r.Description,""); // title, author, subject, company
//Create a utility object
pdfUtility=new PdfUtility(anchor);
//write out the header
int size=0;
tw.Write(pdfUtility.GetHeader("1.5",out size),0,size);
filesize = size;
}
public void End()
{
//Write everything
int size=0;
tw.Write(catalog.GetCatalogDict(outline.GetObjectNumber(), pageTree.objectNum,
filesize,out size),0,size);
filesize += size;
tw.Write(pageTree.GetPageTree(filesize,out size),0,size);
filesize += size;
tw.Write(fonts.GetFontDict(filesize,out size),0,size);
filesize += size;
tw.Write(patterns.GetPatternDict(filesize, out size), 0, size);
filesize += size;
if (images.Images.Count > 0)
{
tw.Write(images.GetImageDict(filesize,out size),0,size);
filesize += size;
}
if (outline.Bookmarks.Count > 0)
{
tw.Write(outline.GetOutlineDict(filesize, out size), 0, size);
filesize += size;
}
tw.Write(info.GetInfoDict(filesize,out size),0,size);
filesize += size;
tw.Write(pdfUtility.CreateXrefTable(filesize,out size),0,size);
filesize += size;
tw.Write(pdfUtility.GetTrailer(catalog.objectNum,
info.objectNum,out size),0,size);
filesize += size;
return;
}
public void RunPages(Pages pgs) // this does all the work
{
foreach (Page p in pgs)
{
//Create a Page Dictionary representing a visible page
page=new PdfPage(anchor);
content=new PdfContent(anchor);
PdfPageSize pSize=new PdfPageSize((int) r.ReportDefinition.PageWidth.Points,
(int) r.ReportDefinition.PageHeight.Points);
page.CreatePage(pageTree.objectNum,pSize);
pageTree.AddPage(page.objectNum);
//Create object that presents the elements in the page
elements=new PdfElements(page, pSize);
ProcessPage(pgs, p);
// after a page
content.SetStream(elements.EndElements());
page.AddResource(fonts,content.objectNum);
page.AddResource(patterns,content.objectNum);
//get the pattern colorspace...
PatternObj po = new PatternObj(anchor);
page.AddResource(po,content.objectNum);
int size=0;
tw.Write(page.GetPageDict(filesize,out size),0,size);
filesize += size;
tw.Write(content.GetContentDict(filesize,out size),0,size);
filesize += size;
tw.Write(po.GetPatternObj(filesize, out size),0,size);
filesize += size;
}
return;
}
// render all the objects in a page in PDF
private void ProcessPage(Pages pgs, IEnumerable items)
{
foreach (PageItem pi in items)
{
if (pi.SI.BackgroundImage != null)
{ // put out any background image
PageImage bgImg = pi.SI.BackgroundImage;
// elements.AddImage(images, i.Name, content.objectNum, i.SI, i.ImgFormat,
// pi.X, pi.Y, pi.W, pi.H, i.ImageData,i.SamplesW, i.SamplesH, null);
//Duc Phan modified 10 Dec, 2007 to support on background image
float imW = RSize.PointsFromPixels(pgs.G, bgImg.SamplesW);
float imH = RSize.PointsFromPixels(pgs.G, bgImg.SamplesH);
int repeatX = 0;
int repeatY = 0;
float itemW = pi.W - (pi.SI.PaddingLeft + pi.SI.PaddingRight);
float itemH = pi.H - (pi.SI.PaddingTop + pi.SI.PaddingBottom);
switch (bgImg.Repeat)
{
case ImageRepeat.Repeat:
repeatX = (int)Math.Floor(itemW / imW);
repeatY = (int)Math.Floor(itemH / imH);
break;
case ImageRepeat.RepeatX:
repeatX = (int)Math.Floor(itemW / imW);
repeatY = 1;
break;
case ImageRepeat.RepeatY:
repeatY = (int)Math.Floor(itemH / imH);
repeatX = 1;
break;
case ImageRepeat.NoRepeat:
default:
repeatX = repeatY = 1;
break;
}
//make sure the image is drawn at least 1 times
repeatX = Math.Max(repeatX, 1);
repeatY = Math.Max(repeatY, 1);
float currX = pi.X + pi.SI.PaddingLeft;
float currY = pi.Y + pi.SI.PaddingTop;
float startX = currX;
float startY = currY;
for (int i = 0; i < repeatX; i++)
{
for (int j = 0; j < repeatY; j++)
{
currX = startX + i * imW;
currY = startY + j * imH;
elements.AddImage(images, bgImg.Name,
content.objectNum, bgImg.SI, bgImg.ImgFormat,
currX, currY, imW, imH, RectangleF.Empty, bgImg.ImageData, bgImg.SamplesW, bgImg.SamplesH, null,pi.Tooltip);
}
}
}
if (pi is PageTextHtml)
{
PageTextHtml pth = pi as PageTextHtml;
pth.Build(pgs.G);
ProcessPage(pgs, pth);
continue;
}
if (pi is PageText)
{
PageText pt = pi as PageText;
float[] textwidth;
string[] sa = MeasureString(pt, pgs.G, out textwidth);
elements.AddText(pt.X, pt.Y, pt.H, pt.W, sa, pt.SI,
fonts, textwidth, pt.CanGrow, pt.HyperLink, pt.NoClip,pt.Tooltip);
if (pt.Bookmark != null)
{
outline.Bookmarks.Add(new PdfOutlineEntry(anchor, page.objectNum, pt.Bookmark, pt.X, elements.PageSize.yHeight - pt.Y));
}
continue;
}
if (pi is PageLine)
{
PageLine pl = pi as PageLine;
elements.AddLine(pl.X, pl.Y, pl.X2, pl.Y2, pl.SI);
continue;
}
if (pi is PageEllipse)
{
PageEllipse pe = pi as PageEllipse;
elements.AddEllipse(pe.X, pe.Y, pe.H, pe.W, pe.SI, pe.HyperLink);
continue;
}
if (pi is PageImage)
{
//PageImage i = pi as PageImage;
//float x = i.X + i.SI.PaddingLeft;
//float y = i.Y + i.SI.PaddingTop;
//float w = i.W - i.SI.PaddingLeft - i.SI.PaddingRight;
//float h = i.H - i.SI.PaddingTop - i.SI.PaddingBottom;
//elements.AddImage(images, i.Name, content.objectNum, i.SI, i.ImgFormat,
// x, y, w, h, i.ImageData,i.SamplesW, i.SamplesH, i.HyperLink);
//continue;
PageImage i = pi as PageImage;
//Duc Phan added 20 Dec, 2007 to support sized image
RectangleF r2 = new RectangleF(i.X + i.SI.PaddingLeft, i.Y + i.SI.PaddingTop, i.W - i.SI.PaddingLeft - i.SI.PaddingRight, i.H - i.SI.PaddingTop - i.SI.PaddingBottom);
RectangleF adjustedRect; // work rectangle
RectangleF clipRect = RectangleF.Empty;
switch (i.Sizing)
{
case ImageSizingEnum.AutoSize:
adjustedRect = new RectangleF(r2.Left, r2.Top,
r2.Width, r2.Height);
break;
case ImageSizingEnum.Clip:
adjustedRect = new RectangleF(r2.Left, r2.Top,
RSize.PointsFromPixels(pgs.G, i.SamplesW), RSize.PointsFromPixels(pgs.G,i.SamplesH));
clipRect = new RectangleF(r2.Left, r2.Top,
r2.Width, r2.Height);
break;
case ImageSizingEnum.FitProportional:
float height;
float width;
float ratioIm = (float)i.SamplesH / i.SamplesW;
float ratioR = r2.Height / r2.Width;
height = r2.Height;
width = r2.Width;
if (ratioIm > ratioR)
{ // this means the rectangle width must be corrected
width = height * (1 / ratioIm);
}
else if (ratioIm < ratioR)
{ // this means the rectangle height must be corrected
height = width * ratioIm;
}
adjustedRect = new RectangleF(r2.X, r2.Y, width, height);
break;
case ImageSizingEnum.Fit:
default:
adjustedRect = r2;
break;
}
if (i.ImgFormat == System.Drawing.Imaging.ImageFormat.Wmf || i.ImgFormat == System.Drawing.Imaging.ImageFormat.Emf)
{
//We dont want to add it - its already been broken down into page items;
}
else
{
elements.AddImage(images, i.Name, content.objectNum, i.SI, i.ImgFormat,
adjustedRect.X, adjustedRect.Y, adjustedRect.Width, adjustedRect.Height, clipRect, i.ImageData, i.SamplesW, i.SamplesH, i.HyperLink,i.Tooltip);
}
continue;
}
if (pi is PageRectangle)
{
PageRectangle pr = pi as PageRectangle;
elements.AddRectangle(pr.X, pr.Y, pr.H, pr.W, pi.SI, pi.HyperLink, patterns, pi.Tooltip);
continue;
}
if (pi is PagePie)
{ // TODO
PagePie pp = pi as PagePie;
// elements.AddPie(pr.X, pr.Y, pr.H, pr.W, pi.SI, pi.HyperLink, patterns, pi.Tooltip);
continue;
}
if (pi is PagePolygon)
{
PagePolygon ppo = pi as PagePolygon;
elements.AddPolygon(ppo.Points, pi.SI, pi.HyperLink, patterns);
continue;
}
if (pi is PageCurve)
{
PageCurve pc = pi as PageCurve;
elements.AddCurve(pc.Points, pi.SI);
continue;
}
}
}
private string[] MeasureString(PageText pt, Graphics g, out float[] width)
{
StyleInfo si = pt.SI;
string s = pt.Text;
Font drawFont=null;
StringFormat drawFormat=null;
SizeF ms;
string[] sa=null;
width=null;
try
{
// STYLE
System.Drawing.FontStyle fs = 0;
if (si.FontStyle == FontStyleEnum.Italic)
fs |= System.Drawing.FontStyle.Italic;
// WEIGHT
switch (si.FontWeight)
{
case FontWeightEnum.Bold:
case FontWeightEnum.Bolder:
case FontWeightEnum.W500:
case FontWeightEnum.W600:
case FontWeightEnum.W700:
case FontWeightEnum.W800:
case FontWeightEnum.W900:
fs |= System.Drawing.FontStyle.Bold;
break;
default:
break;
}
drawFont = new Font(StyleInfo.GetFontFamily(si.FontFamilyFull), si.FontSize, fs);
drawFormat = new StringFormat();
drawFormat.Alignment = StringAlignment.Near;
// Measure string
// pt.NoClip indicates that this was generated by PageTextHtml Build. It has already word wrapped.
if (pt.NoClip || pt.SI.WritingMode == WritingModeEnum.tb_rl) // TODO: support multiple lines for vertical text
{
ms = MeasureString(s, g, drawFont, drawFormat);
width = new float[1];
width[0] = RSize.PointsFromPixels(g, ms.Width); // convert to points from pixels
sa = new string[1];
sa[0] = s;
return sa;
}
// handle multiple lines;
// 1) split the string into the forced line breaks (ie "\n and \r")
// 2) foreach of the forced line breaks; break these into words and recombine
s = s.Replace("\r\n", "\n"); // don't want this to result in double lines
string[] flines = s.Split(lineBreak);
List<string> lines = new List<string>();
List<float> lineWidths = new List<float>();
// remove the size reserved for left and right padding
float ptWidth = pt.W - pt.SI.PaddingLeft - pt.SI.PaddingRight;
if (ptWidth <= 0)
ptWidth = 1;
foreach (string tfl in flines)
{
string fl;
if (tfl.Length > 0 && tfl[tfl.Length-1] == ' ')
fl = tfl.TrimEnd(' ');
else
fl = tfl;
// Check if entire string fits into a line
ms = MeasureString(fl, g, drawFont, drawFormat);
float tw = RSize.PointsFromPixels(g, ms.Width);
if (tw <= ptWidth)
{ // line fits don't need to break it down further
lines.Add(fl);
lineWidths.Add(tw);
continue;
}
// Line too long; need to break into multiple lines
// 1) break line into parts; then build up again keeping track of word positions
string[] parts = fl.Split(wordBreak); // this is the maximum split of lines
StringBuilder sb = new StringBuilder(fl.Length);
CharacterRange[] cra = new CharacterRange[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
int sc = sb.Length; // starting character
sb.Append(parts[i]); // endding character
if (i != parts.Length - 1) // last item doesn't need blank
sb.Append(" ");
int ec = sb.Length;
CharacterRange cr = new CharacterRange(sc, ec - sc);
cra[i] = cr; // add to character array
}
// 2) Measure the word locations within the line
string wfl = sb.ToString();
WordStartFinish[] wordLocations = MeasureString(wfl, g, drawFont, drawFormat, cra);
if (wordLocations == null)
continue;
// 3) Loop thru creating new lines as needed
int startLoc = 0;
CharacterRange crs = cra[startLoc];
CharacterRange cre = cra[startLoc];
float cwidth = wordLocations[0].end; // length of the first
float bwidth = wordLocations[0].start; // characters need a little extra on start
string ts;
bool bLine = true;
for (int i=1; i < cra.Length; i++)
{
cwidth = wordLocations[i].end - wordLocations[startLoc].start + bwidth;
if (cwidth > ptWidth)
{ // time for a new line
cre = cra[i-1];
ts = wfl.Substring(crs.First, cre.First + cre.Length - crs.First);
lines.Add(ts);
lineWidths.Add(wordLocations[i-1].end - wordLocations[startLoc].start + bwidth);
// Find the first non-blank character of the next line
while (i < cra.Length &&
cra[i].Length == 1 &&
fl[cra[i].First] == ' ')
{
i++;
}
if (i < cra.Length) // any lines left?
{ // yes, continue on
startLoc = i;
crs = cre = cra[startLoc];
cwidth = wordLocations[i].end - wordLocations[startLoc].start + bwidth;
}
else // no, we can stop
bLine = false;
// bwidth = wordLocations[startLoc].start - wordLocations[startLoc - 1].end;
}
else
cre = cra[i];
}
if (bLine)
{
ts = fl.Substring(crs.First, cre.First + cre.Length - crs.First);
lines.Add(ts);
lineWidths.Add(cwidth);
}
}
// create the final array from the Lists
string[] la = lines.ToArray();
width = lineWidths.ToArray();
return la;
}
finally
{
if (drawFont != null)
drawFont.Dispose();
if (drawFormat != null)
drawFont.Dispose();
}
}
/// <summary>
/// Measures the location of an arbritrary # of words within a string
/// </summary>
private WordStartFinish[] MeasureString(string s, Graphics g, Font drawFont, StringFormat drawFormat, CharacterRange[] cra)
{
if (cra.Length <= MEASUREMAX) // handle the simple case of < MEASUREMAX words
return MeasureString32(s, g, drawFont, drawFormat, cra);
// Need to compensate for SetMeasurableCharacterRanges limitation of 32 (MEASUREMAX)
int mcra = (cra.Length / MEASUREMAX); // # of full 32 arrays we need
int ip = cra.Length % MEASUREMAX; // # of partial entries needed for last array (if any)
WordStartFinish[] sz = new WordStartFinish[cra.Length]; // this is the final result;
float startPos=0;
CharacterRange[] cra32 = new CharacterRange[MEASUREMAX]; // fill out
int icra=0; // index thru the cra
for (int i=0; i < mcra; i++)
{
// fill out the new array
int ticra = icra;
for (int j=0; j < cra32.Length; j++)
{
cra32[j] = cra[ticra++];
cra32[j].First -= cra[icra].First; // adjust relative offsets of strings
}
// measure the word locations (in the new string)
// ???? should I put a blank in front of it??
string ts = s.Substring(cra[icra].First,
cra[icra + cra32.Length-1].First + cra[icra + cra32.Length-1].Length - cra[icra].First);
WordStartFinish[] pos = MeasureString32(ts, g, drawFont, drawFormat, cra32);
// copy the values adding in the new starting positions
for (int j = 0; j < pos.Length; j++)
{
sz[icra].start = pos[j].start + startPos;
sz[icra++].end = pos[j].end + startPos;
}
startPos = sz[icra-1].end; // reset the start position for the next line
}
// handle the remaining character
if (ip > 0)
{
// resize the range array
cra32 = new CharacterRange[ip];
// fill out the new array
int ticra = icra;
for (int j=0; j < cra32.Length; j++)
{
cra32[j] = cra[ticra++];
cra32[j].First -= cra[icra].First; // adjust relative offsets of strings
}
// measure the word locations (in the new string)
// ???? should I put a blank in front of it??
string ts = s.Substring(cra[icra].First,
cra[icra + cra32.Length-1].First + cra[icra + cra32.Length-1].Length - cra[icra].First);
WordStartFinish[] pos = MeasureString32(ts, g, drawFont, drawFormat, cra32);
// copy the values adding in the new starting positions
for (int j = 0; j < pos.Length; j++)
{
sz[icra].start = pos[j].start + startPos;
sz[icra++].end = pos[j].end + startPos;
}
}
return sz;
}
/// <summary>
/// Measures the location of words within a string; limited by .Net 1.1 to 32 words
/// MEASUREMAX is a constant that defines that limit
/// </summary>
/// <param name="s"></param>
/// <param name="g"></param>
/// <param name="drawFont"></param>
/// <param name="drawFormat"></param>
/// <param name="cra"></param>
/// <returns></returns>
private WordStartFinish[] MeasureString32(string s, Graphics g, Font drawFont, StringFormat drawFormat, CharacterRange[] cra)
{
if (s == null || s.Length == 0)
return null;
drawFormat.SetMeasurableCharacterRanges(cra);
Region[] rs = new Region[cra.Length];
rs = g.MeasureCharacterRanges(s, drawFont, new RectangleF(0, 0, float.MaxValue, float.MaxValue),
drawFormat);
WordStartFinish[] sz = new WordStartFinish[cra.Length];
int isz = 0;
foreach (Region r in rs)
{
RectangleF mr = r.GetBounds(g);
sz[isz].start = RSize.PointsFromPixels(g, mr.Left);
sz[isz].end = RSize.PointsFromPixels(g, mr.Right);
isz++;
}
return sz;
}
struct WordStartFinish
{
internal float start;
internal float end;
}
private SizeF MeasureString(string s, Graphics g, Font drawFont, StringFormat drawFormat)
{
if (s == null || s.Length == 0)
return SizeF.Empty;
CharacterRange[] cr = {new CharacterRange(0, s.Length)};
drawFormat.SetMeasurableCharacterRanges(cr);
Region[] rs = new Region[1];
rs = g.MeasureCharacterRanges(s, drawFont, new RectangleF(0,0,float.MaxValue,float.MaxValue),
drawFormat);
RectangleF mr = rs[0].GetBounds(g);
return new SizeF(mr.Width, mr.Height);
}
private float MeasureStringBlank(Graphics g, Font drawFont, StringFormat drawFormat)
{
SizeF ms = MeasureString(" ", g, drawFont, drawFormat);
float width = RSize.PointsFromPixels(g, ms.Width); // convert to points from pixels
return width*2;
}
// Body: main container for the report
public void BodyStart(Body b)
{
}
public void BodyEnd(Body b)
{
}
public void PageHeaderStart(PageHeader ph)
{
}
public void PageHeaderEnd(PageHeader ph)
{
}
public void PageFooterStart(PageFooter pf)
{
}
public void PageFooterEnd(PageFooter pf)
{
}
public void Textbox(Textbox tb, string t, Row row)
{
}
public void DataRegionNoRows(DataRegion d, string noRowsMsg)
{
}
// Lists
public bool ListStart(List l, Row r)
{
return true;
}
public void ListEnd(List l, Row r)
{
}
public void ListEntryBegin(List l, Row r)
{
}
public void ListEntryEnd(List l, Row r)
{
}
// Tables // Report item table
public bool TableStart(Table t, Row row)
{
return true;
}
public void TableEnd(Table t, Row row)
{
}
public void TableBodyStart(Table t, Row row)
{
}
public void TableBodyEnd(Table t, Row row)
{
}
public void TableFooterStart(Footer f, Row row)
{
}
public void TableFooterEnd(Footer f, Row row)
{
}
public void TableHeaderStart(Header h, Row row)
{
}
public void TableHeaderEnd(Header h, Row row)
{
}
public void TableRowStart(TableRow tr, Row row)
{
}
public void TableRowEnd(TableRow tr, Row row)
{
}
public void TableCellStart(TableCell t, Row row)
{
return;
}
public void TableCellEnd(TableCell t, Row row)
{
return;
}
public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) // called first
{
return true;
}
public void MatrixColumns(Matrix m, MatrixColumns mc) // called just after MatrixStart
{
}
public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan)
{
}
public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r)
{
}
public void MatrixRowStart(Matrix m, int row, Row r)
{
}
public void MatrixRowEnd(Matrix m, int row, Row r)
{
}
public void MatrixEnd(Matrix m, Row r) // called last
{
}
public void Chart(Chart c, Row r, ChartBase cb)
{
}
public void Image(fyiReporting.RDL.Image i, Row r, string mimeType, Stream ior)
{
}
public void Line(Line l, Row r)
{
return;
}
public bool RectangleStart(RDL.Rectangle rect, Row r)
{
return true;
}
public void RectangleEnd(RDL.Rectangle rect, Row r)
{
}
public void Subreport(Subreport s, Row r)
{
}
public void GroupingStart(Grouping g) // called at start of grouping
{
}
public void GroupingInstanceStart(Grouping g) // called at start for each grouping instance
{
}
public void GroupingInstanceEnd(Grouping g) // called at start for each grouping instance
{
}
public void GroupingEnd(Grouping g) // called at end of grouping
{
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
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.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for ReportCtl.
/// </summary>
internal class MatrixCtl : System.Windows.Forms.UserControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
bool fDataSet, fPBBefore, fPBAfter, fNoRows, fCellDataElementOutput, fCellDataElementName;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox cbDataSet;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox chkPBBefore;
private System.Windows.Forms.CheckBox chkPBAfter;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbNoRows;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.CheckBox chkCellContents;
private System.Windows.Forms.TextBox tbCellDataElementName;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal MatrixCtl(DesignXmlDraw dxDraw, List<XmlNode> ris)
{
_ReportItems = ris;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
XmlNode riNode = _ReportItems[0];
tbNoRows.Text = _Draw.GetElementValue(riNode, "NoRows", "");
cbDataSet.Items.AddRange(_Draw.DataSetNames);
cbDataSet.Text = _Draw.GetDataSetNameValue(riNode);
if (_Draw.GetReportItemDataRegionContainer(riNode) != null)
cbDataSet.Enabled = false;
chkPBBefore.Checked = _Draw.GetElementValue(riNode, "PageBreakAtStart", "false").ToLower()=="true"? true:false;
chkPBAfter.Checked = _Draw.GetElementValue(riNode, "PageBreakAtEnd", "false").ToLower()=="true"? true:false;
this.chkCellContents.Checked = _Draw.GetElementValue(riNode, "CellDataElementOutput", "Output")=="Output"?true:false;
this.tbCellDataElementName.Text = _Draw.GetElementValue(riNode, "CellDataElementName", "Cell");
fNoRows = fDataSet = fPBBefore = fPBAfter = fCellDataElementOutput = fCellDataElementName = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MatrixCtl));
this.label2 = new System.Windows.Forms.Label();
this.cbDataSet = new System.Windows.Forms.ComboBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.chkPBAfter = new System.Windows.Forms.CheckBox();
this.chkPBBefore = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.tbNoRows = new System.Windows.Forms.TextBox();
this.tbCellDataElementName = new System.Windows.Forms.TextBox();
this.chkCellContents = new System.Windows.Forms.CheckBox();
this.label3 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// cbDataSet
//
resources.ApplyResources(this.cbDataSet, "cbDataSet");
this.cbDataSet.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbDataSet.Name = "cbDataSet";
this.cbDataSet.SelectedIndexChanged += new System.EventHandler(this.cbDataSet_SelectedIndexChanged);
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Controls.Add(this.chkPBAfter);
this.groupBox1.Controls.Add(this.chkPBBefore);
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// chkPBAfter
//
resources.ApplyResources(this.chkPBAfter, "chkPBAfter");
this.chkPBAfter.Name = "chkPBAfter";
this.chkPBAfter.CheckedChanged += new System.EventHandler(this.chkPBAfter_CheckedChanged);
//
// chkPBBefore
//
resources.ApplyResources(this.chkPBBefore, "chkPBBefore");
this.chkPBBefore.Name = "chkPBBefore";
this.chkPBBefore.CheckedChanged += new System.EventHandler(this.chkPBBefore_CheckedChanged);
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// tbNoRows
//
resources.ApplyResources(this.tbNoRows, "tbNoRows");
this.tbNoRows.Name = "tbNoRows";
this.tbNoRows.TextChanged += new System.EventHandler(this.tbNoRows_TextChanged);
//
// tbCellDataElementName
//
resources.ApplyResources(this.tbCellDataElementName, "tbCellDataElementName");
this.tbCellDataElementName.Name = "tbCellDataElementName";
this.tbCellDataElementName.TextChanged += new System.EventHandler(this.tbCellDataElementName_TextChanged);
//
// chkCellContents
//
resources.ApplyResources(this.chkCellContents, "chkCellContents");
this.chkCellContents.Name = "chkCellContents";
this.chkCellContents.CheckedChanged += new System.EventHandler(this.chkCellContents_CheckedChanged);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// groupBox2
//
resources.ApplyResources(this.groupBox2, "groupBox2");
this.groupBox2.Controls.Add(this.tbCellDataElementName);
this.groupBox2.Controls.Add(this.chkCellContents);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Name = "groupBox2";
this.groupBox2.TabStop = false;
//
// MatrixCtl
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.tbNoRows);
this.Controls.Add(this.label1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.cbDataSet);
this.Controls.Add(this.label2);
this.Name = "MatrixCtl";
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
// No more changes
fNoRows = fDataSet = fPBBefore = fPBAfter= fCellDataElementOutput = fCellDataElementName = false;
}
public void ApplyChanges(XmlNode node)
{
if (fNoRows)
_Draw.SetElement(node, "NoRows", this.tbNoRows.Text);
if (fDataSet)
_Draw.SetElement(node, "DataSetName", this.cbDataSet.Text);
if (fPBBefore)
_Draw.SetElement(node, "PageBreakAtStart", this.chkPBBefore.Checked? "true":"false");
if (fPBAfter)
_Draw.SetElement(node, "PageBreakAtEnd", this.chkPBAfter.Checked? "true":"false");
if (fCellDataElementOutput)
_Draw.SetElement(node, "CellDataElementOutput", this.chkCellContents.Checked? "Output":"NoOutput");
if (fCellDataElementName)
{
if (this.tbCellDataElementName.Text.Length > 0)
_Draw.SetElement(node, "CellDataElementName", this.tbCellDataElementName.Text);
else
_Draw.RemoveElement(node, "CellDataElementName");
}
}
private void cbDataSet_SelectedIndexChanged(object sender, System.EventArgs e)
{
fDataSet = true;
}
private void chkPBBefore_CheckedChanged(object sender, System.EventArgs e)
{
fPBBefore = true;
}
private void chkPBAfter_CheckedChanged(object sender, System.EventArgs e)
{
fPBAfter = true;
}
private void tbNoRows_TextChanged(object sender, System.EventArgs e)
{
fNoRows = true;
}
private void tbCellDataElementName_TextChanged(object sender, System.EventArgs e)
{
fCellDataElementName = true;
}
private void chkCellContents_CheckedChanged(object sender, System.EventArgs e)
{
this.fCellDataElementOutput = true;
}
}
}
| |
/*
* Single.cs - Implementation of the "System.Single" class.
*
* Copyright (C) 2001 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
*/
namespace System
{
#if CONFIG_EXTENDED_NUMERICS
using System.Private;
using System.Private.NumberFormat;
using System.Globalization;
using System.Runtime.CompilerServices;
public struct Single : IComparable, IFormattable
#if !ECMA_COMPAT
, IConvertible
#endif
{
private float value_;
#if __CSCC__
public const float MinValue = __builtin_constant("float_min");
public const float Epsilon = __builtin_constant("float_epsilon");
public const float MaxValue = __builtin_constant("float_max");
#else
public const float MinValue = -3.40282346638528859e38f;
public const float Epsilon = 1.4e-45f;
public const float MaxValue = 3.40282346638528859e38f;
#endif
public const float PositiveInfinity = (1.0f / 0.0f);
public const float NegativeInfinity = (-1.0f / 0.0f);
public const float NaN = (0.0f / 0.0f);
// Override inherited methods.
public override int GetHashCode()
{
if(value_ >= 0.0)
{
return unchecked((int)value_);
}
else
{
return unchecked(-(int)value_);
}
}
public override bool Equals(Object value)
{
if(value is Single)
{
return (value_ == ((Single)value).value_);
}
else
{
return false;
}
}
// String conversion.
public override String ToString()
{
return ToString(null, null);
}
public String ToString(String format)
{
return ToString(format, null);
}
public String ToString(IFormatProvider provider)
{
return ToString(null, provider);
}
public String ToString(String format, IFormatProvider provider)
{
if (format == null) format = "G";
return
Formatter.CreateFormatter(format).Format(this, provider);
}
// Value testing methods.
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static bool IsNaN(float f);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static int TestInfinity(float f);
public static bool IsInfinity(float f)
{
return (TestInfinity(f) != 0);
}
public static bool IsPositiveInfinity(float f)
{
return (TestInfinity(f) > 0);
}
public static bool IsNegativeInfinity(float f)
{
return (TestInfinity(f) < 0);
}
// Parsing methods.
public static float Parse(String s, NumberStyles style,
IFormatProvider provider)
{
NumberFormatInfo nfi = NumberFormatInfo.GetInstance(provider);
try
{
return NumberParser.ParseSingle(s, style, nfi);
}
catch(FormatException)
{
String temp = s.Trim();
if(temp.Equals(nfi.PositiveInfinitySymbol))
{
return PositiveInfinity;
}
else if(temp.Equals(nfi.NegativeInfinitySymbol))
{
return NegativeInfinity;
}
else if(temp.Equals(nfi.NaNSymbol))
{
return NaN;
}
throw;
}
}
public static float Parse(String s)
{
return Parse(s, NumberStyles.Float |
NumberStyles.AllowThousands, null);
}
public static float Parse(String s, IFormatProvider provider)
{
return Parse(s, NumberStyles.Float |
NumberStyles.AllowThousands, provider);
}
public static float Parse(String s, NumberStyles style)
{
return Parse(s, style, null);
}
// Implementation of the IComparable interface.
public int CompareTo(Object value)
{
if(value != null)
{
if(value is Single)
{
float val1 = value_;
float val2 = ((Single)value).value_;
if(val1 < val2)
{
return -1;
}
else if(val1 > val2)
{
return 1;
}
else if(val1 == val2)
{
return 0;
}
else if(IsNaN(val1))
{
if(IsNaN(val2))
{
return 0;
}
else
{
return -1;
}
}
else
{
return 1;
}
}
else
{
throw new ArgumentException(_("Arg_MustBeSingle"));
}
}
else
{
return 1;
}
}
#if !ECMA_COMPAT
// Implementation of the IConvertible interface.
public TypeCode GetTypeCode()
{
return TypeCode.Single;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(value_);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(value_);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(value_);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(value_);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(value_);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "Single", "Char"));
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(value_);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(value_);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(value_);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(value_);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return value_;
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(value_);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(value_);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException
(String.Format
(_("InvalidCast_FromTo"), "Single", "DateTime"));
}
Object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return Convert.DefaultToType(this, conversionType,
provider, true);
}
#endif // !ECMA_COMPAT
}; // class Single
#endif // CONFIG_EXTENDED_NUMERICS
}; // namespace System
| |
//#define dbg_level_1
//#define dbg_level_2
#define dbg_controls
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Vexe.Editor.Helpers;
using Vexe.Runtime.Extensions;
using Vexe.Runtime.Helpers;
using Vexe.Runtime.Types;
using UnityObject = UnityEngine.Object;
namespace Vexe.Editor.GUIs
{
public class RabbitGUI : BaseGUI, IDisposable
{
public Action OnFinishedLayoutReserve, OnRepaint;
public float Height { private set; get; }
public float Width { private set; get; }
public override Rect LastRect
{
get
{
if (!_allocatedMemory)
return kDummyRect;
if (_nextControlIdx == 0)
throw new InvalidOperationException("Can't get last rect - there are no previous controls to get the last rect from");
if (_nextControlIdx - 1 >= _controls.Count)
{
#if dbg_level_1
Debug.Log("Last rect out of range. Returning dummy rect. If that's causing problems, maybe request a seek instead. nextControlIdx {0}. controls.Count {1}".FormatWith(_nextControlIdx, _controls.Count));
#endif
return kDummyRect; // or maybe request reset?
}
return _controls[_nextControlIdx - 1].rect;
}
}
private enum GUIPhase { Layout, Draw }
private GUIPhase _currentPhase;
private List<GUIControl> _controls;
private List<GUIBlock> _blocks;
private Stack<GUIBlock> _blockStack;
private Rect _startRect;
private Rect? _validRect;
private int _nextControlIdx;
private int _nextBlockIdx;
private float _prevInspectorWidth;
private bool _pendingLayout;
private bool _pendingRepaint;
private bool _allocatedMemory;
private bool _storedValidRect;
private int _id;
private static BetterPrefs _prefs;
static MethodCaller<object, string> _scrollableTextArea;
static MethodCaller<object, Gradient> _gradientField;
#if dbg_level_1
private int dbgMaxDepth;
public static void LogCallStack()
{
string stack = RuntimeHelper.GetCallStack();
Debug.Log("Call stack: " + stack);
}
#endif
#if dbg_level_2
private bool m_pendingReset;
private bool _pendingReset
{
get { return m_pendingReset; }
set
{
if (value)
Debug.Log("Setting Reset Request to True! Came from: " + RuntimeHelper.GetCallStack());
m_pendingReset = value;
}
}
#else
private bool _pendingReset;
#endif
public RabbitGUI()
{
_currentPhase = GUIPhase.Layout;
_controls = new List<GUIControl>();
_blocks = new List<GUIBlock>();
_blockStack = new Stack<GUIBlock>();
_prefs = BetterPrefs.GetEditorInstance();
#if dbg_level_1
Debug.Log("Instantiated Rabbit");
#endif
}
static RabbitGUI()
{
var editorGUIType = typeof(EditorGUI);
// ScrollabeTextArea
{
var method = editorGUIType.GetMethod("ScrollableTextAreaInternal",
new Type[] { typeof(Rect), typeof(string), typeof(Vector2).MakeByRefType(), typeof(GUIStyle) },
Flags.StaticAnyVisibility);
_scrollableTextArea = method.DelegateForCall<object, string>();
}
// GradientField
{
var method = editorGUIType.GetMethod("GradientField",
new Type[] { typeof(GUIContent), typeof(Rect), typeof(Gradient) },
Flags.StaticAnyVisibility);
_gradientField = method.DelegateForCall<object, Gradient>();
}
}
void OnEditorUpdate()
{
if (!EditorApplication.isCompiling)
return;
StoreValidRect();
}
void OnPlaymodeChanged()
{
StoreValidRect();
}
void StoreValidRect()
{
if (!_storedValidRect && _validRect.HasValue)
{
var key = RuntimeHelper.CombineHashCodes(_id, "rabbit_coords");
_prefs.Vector3s[key] = new Vector3(_validRect.Value.x, _validRect.Value.y);
_storedValidRect = true;
}
}
public override void OnGUI(Action guiCode, Vector2 padding, int targetId)
{
_id = targetId;
if (!_validRect.HasValue)
{
var key = RuntimeHelper.CombineHashCodes(_id, "rabbit_coords");
Vector3 prevCoords;
if (_prefs.Vector3s.TryGetValue(key, out prevCoords))
{
//Log("Seems we changed play modes and rabbit doesn't have a coord. but we have in store a prev coord from a previous editor session that should work");
var tmp = new Rect();
tmp.x = prevCoords.x;
tmp.y = prevCoords.y;
_validRect = tmp;
}
}
var unityRect = GUILayoutUtility.GetRect(0f, 0f);
if (Event.current.type == EventType.Repaint)
{
if (!_validRect.HasValue || _validRect.Value.y != unityRect.y)
{
_validRect = unityRect;
_pendingLayout = true;
}
}
if (_validRect.HasValue)
{
var start = new Rect(_validRect.Value.x + padding.x, _validRect.Value.y,
EditorGUIUtility.currentViewWidth - padding.y, _validRect.Value.height);
using (Begin(start))
guiCode();
}
GUILayoutUtility.GetRect(EditorGUIUtility.currentViewWidth - 35f, Height);
OnFinishedLayoutReserve.SafeInvoke();
}
public RabbitGUI Begin(Rect start)
{
if (_currentPhase == GUIPhase.Layout)
{
#if dbg_level_1
Debug.Log("Layout phase. Was pending layout: {0}. Was pending reset: {1}".FormatWith(_pendingLayout, _pendingReset));
#endif
Width = start.width;
Height = 0f;
_startRect = start;
_pendingLayout = false;
_pendingReset = false;
}
_nextControlIdx = 0;
_nextBlockIdx = 0;
BeginVertical(GUIStyles.None);
return this;
}
public override void OnEnable()
{
EditorApplication.playmodeStateChanged += OnPlaymodeChanged;
EditorApplication.update += OnEditorUpdate;
}
public override void OnDisable()
{
EditorApplication.playmodeStateChanged -= OnPlaymodeChanged;
EditorApplication.update -= OnEditorUpdate;
}
private void End()
{
_allocatedMemory = true;
var main = _blocks[0];
main.Dispose();
if (_currentPhase == GUIPhase.Layout)
{
main.ResetDimensions();
main.Layout(_startRect);
Height = main.height.Value;
_currentPhase = GUIPhase.Draw;
if (_pendingRepaint)
{
EditorHelper.RepaintAllInspectors();
OnRepaint.SafeInvoke();
_pendingRepaint = false;
}
#if dbg_level_1
Debug.Log("Done layout. Deepest Block depth: {0}. Total number of blocks created: {1}. Total number of controls {2}"
.FormatWith(dbgMaxDepth, _blocks.Count, _controls.Count));
#endif
}
else
{
if (_pendingReset || _nextControlIdx != _controls.Count || _nextBlockIdx != _blocks.Count)
{
#if dbg_level_1
if (_pendingReset)
Debug.Log("Resetting - Theres a reset request pending");
else Debug.Log("Resetting - The number of controls/blocks drawn doesn't match the total number of controls/blocks");
#endif
_controls.Clear();
_blocks.Clear();
_allocatedMemory = false;
_pendingRepaint = true;
_currentPhase = GUIPhase.Layout;
}
else if (_pendingLayout)
{
#if dbg_level_1
Debug.Log("Pending layout request. Doing layout in next phase");
#endif
_currentPhase = GUIPhase.Layout;
EditorHelper.RepaintAllInspectors();
}
else
{
bool resized = _prevInspectorWidth != EditorGUIUtility.currentViewWidth;
if (resized)
{
#if dbg_level_1
Debug.Log("Resized inspector. Doing layout in next phase");
#endif
_prevInspectorWidth = EditorGUIUtility.currentViewWidth;
_currentPhase = GUIPhase.Layout;
}
}
}
}
private T BeginBlock<T>(GUIStyle style) where T : GUIBlock, new()
{
if (_pendingReset)
{
#if dbg_level_1
Debug.Log("Pending reset. Can't begin block of type: " + typeof(T).Name);
#endif
return null;
}
if (_allocatedMemory && _nextBlockIdx >= _blocks.Count)
{
#if dbg_level_1
Debug.Log("Requesting Reset. Can't begin block {0}. We seem to have created controls yet nextBlockIdx {1} > blocks.Count {2}"
.FormatWith(typeof(T).Name, _nextBlockIdx, _blocks.Count));
#endif
_pendingReset = true;
return null;
}
T result;
if (!_allocatedMemory)
{
_blocks.Add(result = new T
{
onDisposed = EndBlock,
data = new ControlData
{
type = typeof(T).Name.ParseEnum<ControlType>(),
style = style,
}
});
if (_blockStack.Count > 0)
{
var owner = _blockStack.Peek();
owner.AddBlock(result);
}
#if dbg_level_1
Debug.Log("Created new block of type {0}. Blocks count {1}. Is pending reset? {2}".FormatWith(typeof(T).Name, _blocks.Count, _pendingReset));
#endif
}
else
{
result = _blocks[_nextBlockIdx] as T;
if (result != null)
{
GUI.Box(result.rect, string.Empty, result.data.style = style);
}
else
{
var requestedType = typeof(T);
var resultType = _blocks[_nextBlockIdx].GetType();
if (requestedType != resultType)
{
#if dbg_level_1
Debug.Log("Requested block result is null. " +
"The type of block requested {0} doesn't match the block type {1} at index {2}. " +
"This is probably due to the occurance of new blocks revealed by a foldout for ex. " +
"Requesting Reset".FormatWith(requestedType.Name, resultType.Name, _nextBlockIdx));
#endif
_pendingReset = true;
return null;
}
#if dbg_level_1
Debug.Log("Result block is null. Count {0}, Idx {1}, Request type {2}".FormatWith(_blocks.Count, _nextBlockIdx, typeof(T).Name));
for (int i = 0; i < _blocks.Count; i++)
Debug.Log("Block {0} at {1} has {2} controls".FormatWith(_blocks[i].data.type.ToString(), i, _blocks[i].controls.Count));
Debug.Log("Block Stack count " + _blockStack.Count);
var array = _blockStack.ToArray();
for (int i = 0; i < array.Length; i++)
Debug.Log("Block {0} at {1} has {2} controls".FormatWith(array[i].data.type.ToString(), i, array[i].controls.Count));
#endif
throw new NullReferenceException("result");
}
}
_nextBlockIdx++;
_blockStack.Push(result);
#if dbg_level_2
Debug.Log("Pushed {0}. Stack {1}. Total {2}. Next {3}".FormatWith(result.GetType().Name, _blockStack.Count, _blocks.Count, _nextBlockIdx));
#endif
#if dbg_level_1
if (_blockStack.Count > dbgMaxDepth)
dbgMaxDepth = _blockStack.Count;
#endif
return result;
}
private void EndBlock()
{
if (!_pendingReset)
_blockStack.Pop();
}
private bool CanDrawControl(out Rect position, ControlData data)
{
position = kDummyRect;
if (_pendingReset)
{
#if dbg_level_1
Debug.Log("Can't draw control of type " + data.type + " There's a Reset pending.");
#endif
return false;
}
if (_nextControlIdx >= _controls.Count && _currentPhase == GUIPhase.Draw)
{
#if dbg_level_1
Debug.Log("Can't draw control of type {0} nextControlIdx {1} is >= controls.Count {2}. Requesting reset".FormatWith(data.type, _nextControlIdx, _controls.Count));
LogCallStack();
#endif
_pendingReset = true;
return false;
}
if (!_allocatedMemory)
{
NewControl(data);
return false;
}
position = _controls[_nextControlIdx++].rect;
return true;
}
private GUIControl NewControl(ControlData data)
{
var parent = _blockStack.Peek();
var control = new GUIControl(data);
parent.controls.Add(control);
_controls.Add(control);
#if dbg_level_2
Debug.Log("Created control {0}. Count {1}".FormatWith(data.type, _controls.Count));
#endif
return control;
}
public void RequestReset()
{
_pendingReset = true;
}
public void RequestLayout()
{
_pendingLayout = true;
}
void IDisposable.Dispose()
{
End();
}
public override IDisposable If(bool condition, IDisposable body)
{
if (condition)
return body;
body.Dispose();
return null;
}
public override Bounds BoundsField(GUIContent content, Bounds value, Layout option)
{
var bounds = new ControlData(content, GUIStyles.None, option, ControlType.Bounds);
Rect position;
if (CanDrawControl(out position, bounds))
{
return EditorGUI.BoundsField(position, content, value);
}
return value;
}
public override Rect Rect(GUIContent content, Rect value, Layout option)
{
var data = new ControlData(content, GUIStyles.None, option, ControlType.RectField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.RectField(position, content, value);
}
return value;
}
public override AnimationCurve Curve (GUIContent content, AnimationCurve value, Layout option)
{
var data = new ControlData (content, GUIStyles.None, option, ControlType.CurveField);
Rect position;
if (CanDrawControl (out position, data))
{
if(value == null)
value = new AnimationCurve();
return EditorGUI.CurveField(position, content, value);
}
return value;
}
public override Gradient GradientField(GUIContent content, Gradient value, Layout option)
{
var data = new ControlData(content, GUIStyles.None, option, ControlType.GradientField);
Rect position;
if (CanDrawControl(out position, data))
{
if (value == null)
value = new Gradient();
return _gradientField(null, new object[] { content, position, value });
}
return value;
}
public override void Box(GUIContent content, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.Box);
Rect position;
if (CanDrawControl(out position, data))
{
GUI.Box(position, content, style);
}
}
public override void HelpBox(string message, MessageType type)
{
var content = GetContent(message);
var height = GUIStyles.HelpBox.CalcHeight(content, Width);
var layout = Layout.sHeight(height);
var data = new ControlData(content, GUIStyles.HelpBox, layout, ControlType.HelpBox);
Rect position;
if (CanDrawControl(out position, data))
{
EditorGUI.HelpBox(position, message, type);
}
}
public override bool Button(GUIContent content, GUIStyle style, Layout option, ControlType buttonType)
{
var data = new ControlData(content, style, option, buttonType);
Rect position;
if (!CanDrawControl(out position, data))
return false;
#if dbg_controls
// due to the inability of unity's debugger to successfully break inside generic classes
// I'm forced to write things this way so I could break when I hit buttons in my drawers,
// since I can't break inside them cause they're generics... Unity...
var pressed = GUI.Button(position, content, style);
if (pressed)
return true;
return false;
#else
return GUI.Button(position, content, style);
#endif
}
public override Color Color(GUIContent content, Color value, Layout option)
{
var data = new ControlData(content, GUIStyles.ColorField, option, ControlType.ColorField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.ColorField(position, content, value);
}
return value;
}
public override Enum EnumPopup(GUIContent content, Enum selected, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.EnumPopup);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.EnumPopup(position, content, selected, style);
}
return selected;
}
public override float Float(GUIContent content, float value, Layout option)
{
var data = new ControlData(content, GUIStyles.NumberField, option, ControlType.Float);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.FloatField(position, content, value);
}
return value;
}
public override bool Foldout(GUIContent content, bool value, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.Foldout);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.Foldout(position, value, content, true, style);
}
return value;
}
public override int Int(GUIContent content, int value, Layout option)
{
var data = new ControlData(content, GUIStyles.NumberField, option, ControlType.IntField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.IntField(position, content, value);
}
return value;
}
public override void Label(GUIContent content, GUIStyle style, Layout option)
{
var label = new ControlData(content, style, option, ControlType.Label);
Rect position;
if (CanDrawControl(out position, label))
{
EditorGUI.LabelField(position, content, style);
}
}
public override int MaskField(GUIContent content, int mask, string[] displayedOptions, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.MaskField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.MaskField(position, content, mask, displayedOptions, style);
}
return mask;
}
public override UnityObject Object(GUIContent content, UnityObject value, Type type, bool allowSceneObjects, Layout option)
{
var data = new ControlData(content, GUIStyles.ObjectField, option, ControlType.ObjectField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.ObjectField(position, content, value, type, allowSceneObjects);
}
return value;
}
public override int Popup(string text, int selectedIndex, string[] displayedOptions, GUIStyle style, Layout option)
{
var content = GetContent(text);
var popup = new ControlData(content, style, option, ControlType.Popup);
Rect position;
if (CanDrawControl(out position, popup))
{
return EditorGUI.Popup(position, content.text, selectedIndex, displayedOptions, style);
}
return selectedIndex;
}
protected override void BeginScrollView(ref Vector2 pos, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background, Layout option)
{
throw new NotImplementedException("I need to implement ExpandWidth and ExpandHeight first, sorry");
}
protected override void EndScrollView()
{
throw new NotImplementedException();
}
public override float FloatSlider(GUIContent content, float value, float leftValue, float rightValue, Layout option)
{
var data = new ControlData(content, GUIStyles.HorizontalSlider, option, ControlType.Slider);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.Slider(position, content, value, leftValue, rightValue);
}
return value;
}
public override void Space(float pixels)
{
if (!_allocatedMemory)
{
var parent = _blockStack.Peek();
var option = parent.Space(pixels);
var space = new ControlData(GUIContent.none, GUIStyle.none, option, ControlType.Space);
NewControl(space);
}
else
{
_nextControlIdx++;
}
}
public override void FlexibleSpace()
{
if (!_allocatedMemory)
{
var flexible = new ControlData(GUIContent.none, GUIStyle.none, null, ControlType.FlexibleSpace);
NewControl(flexible);
}
else
{
_nextControlIdx++;
}
}
public override string Text(GUIContent content, string value, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.TextField);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.TextField(position, content, value, style);
}
return value;
}
public override string ToolbarSearch(string value, Layout option)
{
var data = new ControlData(GetContent(value), GUIStyles.TextField, option, ControlType.TextField);
Rect position;
if (CanDrawControl(out position, data))
{
int searchMode = 0;
return GUIHelper.ToolbarSearchField(null, new object[] { position, null, searchMode, value }) as string;
}
return value;
}
public override bool ToggleLeft(GUIContent content, bool value, GUIStyle labelStyle, Layout option)
{
var data = new ControlData(content, labelStyle, option, ControlType.Toggle);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.ToggleLeft(position, content, value, labelStyle);
}
return value;
}
public override bool Toggle(GUIContent content, bool value, GUIStyle style, Layout option)
{
var data = new ControlData(content, style, option, ControlType.Toggle);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.Toggle(position, content, value, style);
}
return value;
}
protected override HorizontalBlock BeginHorizontal(GUIStyle style)
{
return BeginBlock<HorizontalBlock>(style);
}
protected override VerticalBlock BeginVertical(GUIStyle style)
{
return BeginBlock<VerticalBlock>(style);
}
protected override void EndHorizontal()
{
EndBlock();
}
protected override void EndVertical()
{
EndBlock();
}
public override string TextArea(string value, Layout option)
{
if (option == null)
option = new Layout();
if (!option.height.HasValue)
option.height = 50f;
var data = new ControlData(GetContent(value), GUIStyles.TextArea, option, ControlType.TextArea);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.TextArea(position, value);
}
return value;
}
public override bool InspectorTitlebar(bool foldout, UnityObject target)
{
var data = new ControlData(GUIContent.none, GUIStyles.None, null, ControlType.Foldout);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.InspectorTitlebar(position, foldout, target);
}
return foldout;
}
public override string Tag(GUIContent content, string tag, GUIStyle style, Layout layout)
{
var data = new ControlData(content, style, layout, ControlType.Popup);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.TagField(position, content, tag, style);
}
return tag;
}
public override int LayerField(GUIContent content, int layer, GUIStyle style, Layout layout)
{
var data = new ControlData(content, style, layout, ControlType.Popup);
Rect position;
if (CanDrawControl(out position, data))
{
return EditorGUI.LayerField(position, content, layer, style);
}
return layer;
}
public override void Prefix(string label)
{
if (string.IsNullOrEmpty(label)) return;
var content = GetContent(label);
var style = EditorStyles.label;
var data = new ControlData(content, style, Layout.sWidth(EditorGUIUtility.labelWidth), ControlType.PrefixLabel);
Rect position;
if (CanDrawControl(out position, data))
{
EditorGUI.HandlePrefixLabel(position, position, content, 0, style);
}
}
public override string ScrollableTextArea(string value, ref Vector2 scrollPos, GUIStyle style, Layout option)
{
if (option == null)
option = Layout.None;
if (!option.height.HasValue)
option.height = 50f;
var content = GetContent(value);
var data = new ControlData(content, style, option, ControlType.TextArea);
Rect position;
if (CanDrawControl(out position, data))
{
var args = new object[] { position, value, scrollPos, style };
var newValue = _scrollableTextArea.Invoke(null, args);
scrollPos = (Vector2)args[2];
return newValue;
}
return value;
}
static bool hoveringOnPopup;
static readonly string[] emptyStringArray = new string[0];
public override string TextFieldDropDown(GUIContent label, string value, string[] dropDownElements, Layout option)
{
var data = new ControlData(label, GUIStyles.TextFieldDropDown, option, ControlType.TextFieldDropDown);
Rect totalRect;
if (CanDrawControl(out totalRect, data))
{
Rect textRect = new Rect(totalRect.x, totalRect.y, totalRect.width - GUIStyles.TextFieldDropDown.fixedWidth, totalRect.height);
Rect popupRect = new Rect(textRect.xMax, textRect.y, GUIStyles.TextFieldDropDown.fixedWidth, totalRect.height);
value = EditorGUI.TextField(textRect, "", value, GUIStyles.TextFieldDropDownText);
string[] displayedOptions;
if (dropDownElements.Length > 0)
displayedOptions = dropDownElements;
else
(displayedOptions = new string[1])[0] = "--empty--";
if (popupRect.Contains(Event.current.mousePosition))
hoveringOnPopup = true;
// if there were a lot of options to be displayed, we don't need to always invoke
// Popup cause Unity does a lot of allocation inside and it would have a huge negative impact
// on editor performance so we only display the options when we're hoving over it
if (!hoveringOnPopup)
EditorGUI.Popup(popupRect, string.Empty, -1, emptyStringArray, GUIStyles.TextFieldDropDown);
else
{
EditorGUI.BeginChangeCheck();
int selection = EditorGUI.Popup(popupRect, string.Empty, -1, displayedOptions, GUIStyles.TextFieldDropDown);
if (EditorGUI.EndChangeCheck() && displayedOptions.Length > 0)
{
hoveringOnPopup = false;
value = displayedOptions[selection];
}
}
}
return value;
}
public override double Double(GUIContent content, double value, Layout option)
{
var data = new ControlData(content, GUIStyles.NumberField, option, ControlType.Double);
Rect position;
if (CanDrawControl(out position, data))
return EditorGUI.DoubleField(position, content, value);
return value;
}
public override long Long(GUIContent content, long value, Layout option)
{
var data = new ControlData(content, GUIStyles.NumberField, option, ControlType.Long);
Rect position;
if (CanDrawControl(out position, data))
return EditorGUI.LongField(position, content, value);
return value;
}
public override void MinMaxSlider(GUIContent label, ref float minValue, ref float maxValue, float minLimit, float maxLimit, Layout option)
{
var data = new ControlData(label, GUIStyles.MinMaxSlider, option, ControlType.Slider);
Rect position;
if (CanDrawControl(out position, data))
EditorGUI.MinMaxSlider(label, position, ref minValue, ref maxValue, minLimit, maxLimit);
}
}
}
| |
// 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.Generic;
using System.Security.Principal;
using Xunit;
namespace System.Security.AccessControl.Tests
{
public class RawAcl_CreateFromBinaryForm
{
[Fact]
public static void BasicValidationTestCases()
{
RawAcl rawAcl = null;
byte[] binaryForm = null;
int offset = 0;
GenericAce gAce = null;
byte revision = 0;
int capacity = 0;
//CustomAce constructor parameters
AceType aceType = AceType.AccessAllowed;
AceFlags aceFlag = AceFlags.None;
byte[] opaque = null;
//CompoundAce constructor additional parameters
int accessMask = 0;
CompoundAceType compoundAceType = CompoundAceType.Impersonation;
string sid = "BA";
//CommonAce constructor additional parameters
AceQualifier aceQualifier = 0;
//ObjectAce constructor additional parameters
ObjectAceFlags objectAceFlag = 0;
Guid objectAceType;
Guid inheritedObjectAceType;
//case 1, a valid binary representation with revision 0, 1 SystemAudit CommonAce
revision = 0;
capacity = 1;
rawAcl = new RawAcl(revision, capacity);
gAce = new CommonAce(AceFlags.SuccessfulAccess, AceQualifier.SystemAudit, 1, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null);
rawAcl.InsertAce(0, gAce);
binaryForm = new byte[rawAcl.BinaryLength];
rawAcl.GetBinaryForm(binaryForm, 0);
Assert.True(TestCreateFromBinaryForm(binaryForm, offset, revision, 1, rawAcl.BinaryLength));
//case 2, a valid binary representation with revision 255, 1 AccessAllowed CommonAce
revision = 255;
capacity = 1;
rawAcl = new RawAcl(revision, capacity);
gAce = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, 1, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null);
rawAcl.InsertAce(0, gAce);
binaryForm = new byte[rawAcl.BinaryLength];
rawAcl.GetBinaryForm(binaryForm, 0);
Assert.True(TestCreateFromBinaryForm(binaryForm, offset, revision, 1, rawAcl.BinaryLength));
//case 3, a valid binary representation with revision 127, 1 CustomAce
revision = 127;
capacity = 1;
rawAcl = new RawAcl(revision, capacity);
aceType = AceType.MaxDefinedAceType + 1;
aceFlag = (AceFlags)223; //all flags ored together
opaque = null;
gAce = new CustomAce(aceType, aceFlag, opaque);
rawAcl.InsertAce(0, gAce);
binaryForm = new byte[rawAcl.BinaryLength];
rawAcl.GetBinaryForm(binaryForm, 0);
Assert.True(TestCreateFromBinaryForm(binaryForm, offset, revision, 1, rawAcl.BinaryLength));
//case 4, a valid binary representation with revision 1, 1 CompoundAce
revision = 127;
capacity = 1;
rawAcl = new RawAcl(revision, capacity);
aceFlag = (AceFlags)223; //all flags ored together
accessMask = 1;
compoundAceType = CompoundAceType.Impersonation;
gAce = new CompoundAce(aceFlag, accessMask, compoundAceType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)));
rawAcl.InsertAce(0, gAce);
binaryForm = new byte[rawAcl.BinaryLength];
rawAcl.GetBinaryForm(binaryForm, 0);
Assert.True(TestCreateFromBinaryForm(binaryForm, offset, revision, 1, rawAcl.BinaryLength));
//case 5, a valid binary representation with revision 1, 1 ObjectAce
revision = 127;
capacity = 1;
rawAcl = new RawAcl(revision, capacity);
aceFlag = (AceFlags)223; //all flags ored together
aceQualifier = AceQualifier.AccessAllowed;
accessMask = 1;
objectAceFlag = ObjectAceFlags.ObjectAceTypePresent | ObjectAceFlags.InheritedObjectAceTypePresent;
objectAceType = new Guid("11111111-1111-1111-1111-111111111111");
inheritedObjectAceType = new Guid("22222222-2222-2222-2222-222222222222");
gAce = new ObjectAce(aceFlag, aceQualifier, accessMask, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), objectAceFlag, objectAceType, inheritedObjectAceType, false, null);
rawAcl.InsertAce(0, gAce);
binaryForm = new byte[rawAcl.BinaryLength];
rawAcl.GetBinaryForm(binaryForm, 0);
Assert.True(TestCreateFromBinaryForm(binaryForm, offset, revision, 1, rawAcl.BinaryLength));
//case 6, a valid binary representation with revision 1, no Ace
revision = 127;
capacity = 1;
rawAcl = new RawAcl(revision, capacity);
binaryForm = new byte[rawAcl.BinaryLength];
rawAcl.GetBinaryForm(binaryForm, 0);
Assert.True(TestCreateFromBinaryForm(binaryForm, offset, revision, 0, rawAcl.BinaryLength));
//case 7, a valid binary representation with revision 1, and all Aces from case 1 to 5
revision = 127;
capacity = 5;
rawAcl = new RawAcl(revision, capacity);
//SystemAudit CommonAce
gAce = new CommonAce(AceFlags.SuccessfulAccess, AceQualifier.SystemAudit, 1, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null);
rawAcl.InsertAce(0, gAce);
//Access Allowed CommonAce
gAce = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, 1, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null);
rawAcl.InsertAce(0, gAce);
//CustomAce
aceType = AceType.MaxDefinedAceType + 1;
aceFlag = (AceFlags)223; //all flags ored together
opaque = null;
gAce = new CustomAce(aceType, aceFlag, opaque);
rawAcl.InsertAce(0, gAce);
//CompoundAce
aceFlag = (AceFlags)223; //all flags ored together
accessMask = 1;
compoundAceType = CompoundAceType.Impersonation;
gAce = new CompoundAce(aceFlag, accessMask, compoundAceType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)));
rawAcl.InsertAce(0, gAce);
//ObjectAce
aceFlag = (AceFlags)223; //all flags ored together
aceQualifier = AceQualifier.AccessAllowed;
accessMask = 1;
objectAceFlag = ObjectAceFlags.ObjectAceTypePresent | ObjectAceFlags.InheritedObjectAceTypePresent;
objectAceType = new Guid("11111111-1111-1111-1111-111111111111");
inheritedObjectAceType = new Guid("22222222-2222-2222-2222-222222222222");
gAce = new ObjectAce(aceFlag, aceQualifier, accessMask, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), objectAceFlag, objectAceType, inheritedObjectAceType, false, null);
rawAcl.InsertAce(0, gAce);
binaryForm = new byte[rawAcl.BinaryLength];
rawAcl.GetBinaryForm(binaryForm, 0);
Assert.True(TestCreateFromBinaryForm(binaryForm, offset, revision, 5, rawAcl.BinaryLength));
}
[Fact]
public static void AdditionalTestCases()
{
RawAcl rawAcl = null;
byte[] binaryForm = null;
int offset = 0;
//case 1, binaryForm is null
Assert.Throws<ArgumentNullException>(() =>
{
binaryForm = null;
offset = 0;
rawAcl = new RawAcl(binaryForm, offset);
});
//case 2, binaryForm is empty
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
binaryForm = new byte[0];
offset = 0;
rawAcl = new RawAcl(binaryForm, offset);
});
//case 3, negative offset
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
binaryForm = new byte[100];
offset = -1;
rawAcl = new RawAcl(binaryForm, offset);
});
//case 4, binaryForm length less than GenericAcl.HeaderLength
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
binaryForm = new byte[4];
offset = 0;
rawAcl = new RawAcl(binaryForm, offset);
});
//case 5, a RawAcl of length 64K. RawAcl length = HeaderLength + all ACE's length
// = HeaderLength + (HeaderLength + OpaqueLength) * num_of_custom_ace
// = 8 + ( 4 + OpaqueLength) * num_of_custom_ace
GenericAce gAce = null;
byte revision = 0;
int capacity = 0;
string sid = "BG";
//CustomAce constructor parameters
AceType aceType = 0;
AceFlags aceFlag = 0;
byte[] opaque = null;
revision = 127;
capacity = 1;
rawAcl = new RawAcl(revision, capacity);
aceType = AceType.MaxDefinedAceType + 1;
aceFlag = (AceFlags)223; //all flags ored together
opaque = new byte[GenericAcl.MaxBinaryLength - 3 - 8 - 4];//GenericAcl.MaxBinaryLength = 65535, is not multiple of 4
gAce = new CustomAce(aceType, aceFlag, opaque);
rawAcl.InsertAce(0, gAce);
binaryForm = new byte[rawAcl.BinaryLength];
rawAcl.GetBinaryForm(binaryForm, 0);
Assert.True(TestCreateFromBinaryForm(binaryForm, offset, revision, 1, rawAcl.BinaryLength));
//case 6, a RawAcl of length 64K + 1. RawAcl length = HeaderLength + all ACE's length
// = HeaderLength + (HeaderLength + OpaqueLength) * num_of_custom_ace
// = 8 + ( 4 + OpaqueLength) * num_of_custom_ace
gAce = null;
sid = "BA";
//CustomAce constructor parameters
aceType = 0;
aceFlag = 0;
binaryForm = new byte[65536];
AssertExtensions.Throws<ArgumentException>("binaryForm", () =>
{
revision = 127;
capacity = 1;
rawAcl = new RawAcl(revision, capacity);
rawAcl.GetBinaryForm(binaryForm, 0);
//change the length bytes to 65535
binaryForm[2] = 0xf;
binaryForm[3] = 0xf;
//change the aceCount to 1
binaryForm[4] = 1;
aceType = AceType.MaxDefinedAceType + 1;
aceFlag = (AceFlags)223; //all flags ored together
opaque = new byte[GenericAcl.MaxBinaryLength + 1 - 8 - 4];//GenericAcl.MaxBinaryLength = 65535, is not multiple of 4
gAce = new CustomAce(aceType, aceFlag, opaque);
gAce.GetBinaryForm(binaryForm, 8);
TestCreateFromBinaryForm(binaryForm, 0, revision, 1, binaryForm.Length);
});
//case 7, a valid binary representation with revision 255, 256 Access
//CommonAce to test the correctness of the process of the AceCount in the header
revision = 255;
capacity = 1;
rawAcl = new RawAcl(revision, capacity);
for (int i = 0; i < 256; i++)
{
gAce = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, i + 1, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null);
rawAcl.InsertAce(0, gAce);
}
binaryForm = new byte[rawAcl.BinaryLength + 1000];
rawAcl.GetBinaryForm(binaryForm, 1000);
Assert.True(TestCreateFromBinaryForm(binaryForm, 1000, revision, 256, rawAcl.BinaryLength));
//case 8, array containing garbage
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
binaryForm = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
TestCreateFromBinaryForm(binaryForm, offset, revision, 1, 12);
});
//case 9, array containing garbage
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
//binary form shows the length will be 1, actual length is 12
binaryForm = new byte[] { 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
TestCreateFromBinaryForm(binaryForm, offset, revision, 1, 12);
});
//case 10, array containing garbage
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
binaryForm = new byte[] { 1, 1, 12, 0, 1, 1, 1, 1, 1, 1, 1, 1 };
TestCreateFromBinaryForm(binaryForm, offset, revision, 1, 12);
});
}
private static bool TestCreateFromBinaryForm(byte[] binaryForm, int offset, byte revision, int aceCount, int length)
{
RawAcl rawAcl = null;
byte[] verifierBinaryForm = null;
rawAcl = new RawAcl(binaryForm, offset);
verifierBinaryForm = new byte[rawAcl.BinaryLength];
rawAcl.GetBinaryForm(verifierBinaryForm, 0);
Assert.True(((revision == rawAcl.Revision) &&
Utils.IsBinaryFormEqual(binaryForm, offset, verifierBinaryForm) &&
(aceCount == rawAcl.Count) &&
(length == rawAcl.BinaryLength)));
return true;
}
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using PlayFab.DataModels;
using PlayFab.Internal;
#pragma warning disable 0649
using System;
// This is required for the Obsolete Attribute flag
// which is not always present in all API's
#pragma warning restore 0649
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PlayFab
{
/// <summary>
/// Store arbitrary data associated with an entity. Objects are small (~1KB) JSON-compatible objects which are stored
/// directly on the entity profile. Objects are made available for use in other PlayFab contexts, such as PlayStream events
/// and CloudScript functions. Files can efficiently store data of any size or format. Both objects and files support a
/// flexible permissions system to control read and write access by other entities.
/// </summary>
public class PlayFabDataInstanceAPI
{
public readonly PlayFabApiSettings apiSettings = null;
public readonly PlayFabAuthenticationContext authenticationContext = null;
public PlayFabDataInstanceAPI(PlayFabAuthenticationContext context)
{
if (context == null)
throw new PlayFabException(PlayFabExceptionCode.AuthContextRequired, "Context cannot be null, create a PlayFabAuthenticationContext for each player in advance, or get <PlayFabClientInstanceAPI>.authenticationContext");
authenticationContext = context;
}
public PlayFabDataInstanceAPI(PlayFabApiSettings settings, PlayFabAuthenticationContext context)
{
if (context == null)
throw new PlayFabException(PlayFabExceptionCode.AuthContextRequired, "Context cannot be null, create a PlayFabAuthenticationContext for each player in advance, or get <PlayFabClientInstanceAPI>.authenticationContext");
apiSettings = settings;
authenticationContext = context;
}
/// <summary>
/// Verify entity login.
/// </summary>
public bool IsEntityLoggedIn()
{
return authenticationContext == null ? false : authenticationContext.IsEntityLoggedIn();
}
/// <summary>
/// Clear the Client SessionToken which allows this Client to call API calls requiring login.
/// A new/fresh login will be required after calling this.
/// </summary>
public void ForgetAllCredentials()
{
authenticationContext?.ForgetAllCredentials();
}
/// <summary>
/// Abort pending file uploads to an entity's profile.
/// </summary>
public async Task<PlayFabResult<AbortFileUploadsResponse>> AbortFileUploadsAsync(AbortFileUploadsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/File/AbortFileUploads", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<AbortFileUploadsResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<AbortFileUploadsResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<AbortFileUploadsResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Delete files on an entity's profile.
/// </summary>
public async Task<PlayFabResult<DeleteFilesResponse>> DeleteFilesAsync(DeleteFilesRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/File/DeleteFiles", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<DeleteFilesResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<DeleteFilesResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<DeleteFilesResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Finalize file uploads to an entity's profile.
/// </summary>
public async Task<PlayFabResult<FinalizeFileUploadsResponse>> FinalizeFileUploadsAsync(FinalizeFileUploadsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/File/FinalizeFileUploads", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<FinalizeFileUploadsResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<FinalizeFileUploadsResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<FinalizeFileUploadsResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Retrieves file metadata from an entity's profile.
/// </summary>
public async Task<PlayFabResult<GetFilesResponse>> GetFilesAsync(GetFilesRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/File/GetFiles", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<GetFilesResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetFilesResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<GetFilesResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Retrieves objects from an entity's profile.
/// </summary>
public async Task<PlayFabResult<GetObjectsResponse>> GetObjectsAsync(GetObjectsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Object/GetObjects", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<GetObjectsResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetObjectsResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<GetObjectsResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Initiates file uploads to an entity's profile.
/// </summary>
public async Task<PlayFabResult<InitiateFileUploadsResponse>> InitiateFileUploadsAsync(InitiateFileUploadsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/File/InitiateFileUploads", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<InitiateFileUploadsResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<InitiateFileUploadsResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<InitiateFileUploadsResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Sets objects on an entity's profile.
/// </summary>
public async Task<PlayFabResult<SetObjectsResponse>> SetObjectsAsync(SetObjectsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Object/SetObjects", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<SetObjectsResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<SetObjectsResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<SetObjectsResponse> { Result = result, CustomData = customData };
}
}
}
#endif
| |
using System;
using System.IO;
using System.Reflection;
namespace SIL.Reflection
{
public static class ReflectionHelper
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// Loads a DLL.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Assembly LoadAssembly(string dllPath)
{
try
{
if (!File.Exists(dllPath))
{
string dllFile = Path.GetFileName(dllPath);
string startingDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
dllPath = Path.Combine(startingDir, dllFile);
if (!File.Exists(dllPath))
return null;
}
return Assembly.LoadFrom(dllPath);
}
catch (Exception)
{
return null;
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CreateClassInstance(Assembly assembly, string className)
{
return CreateClassInstance(assembly, className, null);
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CreateClassInstance(Assembly assembly, string className, object[] args)
{
try
{
// First, take a stab at creating the instance with the specified name.
object instance = assembly.CreateInstance(className, false,
BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.NonPublic, null, args, null, null);
if (instance != null)
return instance;
Type[] types = assembly.GetTypes();
// At this point, we know we failed to instantiate a class with the
// specified name, so try to find a type with that name and attempt
// to instantiate the class using the full namespace.
foreach (Type type in types)
{
if (type.Name == className)
{
return assembly.CreateInstance(type.FullName, false,
BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.NonPublic, null, args, null, null);
}
}
}
catch { }
return null;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a string value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static string GetStrResult(object binding, string methodName, object[] args)
{
return (GetResult(binding, methodName, args) as string);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a string value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static string GetStrResult(object binding, string methodName, object args)
{
return (GetResult(binding, methodName, args) as string);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a integer value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static int GetIntResult(object binding, string methodName, object args)
{
return ((int)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a integer value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static int GetIntResult(object binding, string methodName, object[] args)
{
return ((int)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a float value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static float GetFloatResult(object binding, string methodName, object args)
{
return ((float)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a float value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static float GetFloatResult(object binding, string methodName, object[] args)
{
return ((float)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a boolean value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static bool GetBoolResult(object binding, string methodName, object args)
{
return ((bool)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a boolean value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static bool GetBoolResult(object binding, string methodName, object[] args)
{
return ((bool)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName)
{
CallMethod(binding, methodName, null);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object args)
{
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1, object arg2)
{
object[] args = new[] { arg1, arg2 };
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1,
object arg2, object arg3)
{
object[] args = new[] { arg1, arg2, arg3 };
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1,
object arg2, object arg3, object arg4)
{
object[] args = new[] { arg1, arg2, arg3, arg4 };
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object[] args)
{
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns the result of calling a method on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetResult(object binding, string methodName, object args)
{
return Invoke(binding, methodName, new[] { args }, BindingFlags.InvokeMethod);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns the result of calling a method on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetResult(object binding, string methodName, object[] args)
{
return Invoke(binding, methodName, args, BindingFlags.InvokeMethod);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified property on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void SetProperty(object binding, string propertyName, object args)
{
Invoke(binding, propertyName, new[] { args }, BindingFlags.SetProperty);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified field (i.e. member variable) on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void SetField(object binding, string fieldName, object args)
{
Invoke(binding, fieldName, new[] { args }, BindingFlags.SetField);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the specified property on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetProperty(object binding, string propertyName)
{
return Invoke(binding, propertyName, null, BindingFlags.GetProperty);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the specified field (i.e. member variable) on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetField(object binding, string fieldName)
{
return Invoke(binding, fieldName, null, BindingFlags.GetField);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified member variable or property (specified by name) on the
/// specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
private static object Invoke(object binding, string name, object[] args, BindingFlags flags)
{
//if (CanInvoke(binding, name, flags))
{
try
{
return InvokeWithError(binding, name, args, flags);
}
catch { }
}
return null;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding, throwing any exceptions that
/// may occur.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CallMethodWithThrow(object binding, string name, params object[] args)
{
return InvokeWithError(binding, name, args, BindingFlags.InvokeMethod);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified member variable or property (specified by name) on the
/// specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
private static object InvokeWithError(object binding, string name, object[] args, BindingFlags flags)
{
// If binding is a Type then assume invoke on a static method, property or field.
// Otherwise invoke on an instance method, property or field.
flags |= BindingFlags.NonPublic | BindingFlags.Public |
(binding is Type ? BindingFlags.Static : BindingFlags.Instance);
// If necessary, go up the inheritance chain until the name
// of the method, property or field is found.
Type type = binding is Type ? (Type)binding : binding.GetType();
while (type.GetMember(name, flags).Length == 0 && type.BaseType != null)
type = type.BaseType;
return type.InvokeMember(name, flags, null, binding, args);
}
///// ------------------------------------------------------------------------------------
///// <summary>
///// Gets a value indicating whether or not the specified binding contains the field,
///// property or method indicated by name and having the specified flags.
///// </summary>
///// ------------------------------------------------------------------------------------
//private static bool CanInvoke(object binding, string name, BindingFlags flags)
//{
// var srchFlags = (BindingFlags.Public | BindingFlags.NonPublic);
// Type bindingType = null;
// if (binding is Type)
// {
// bindingType = (Type)binding;
// srchFlags |= BindingFlags.Static;
// }
// else
// {
// binding.GetType();
// srchFlags |= BindingFlags.Instance;
// }
// if (((flags & BindingFlags.GetProperty) == BindingFlags.GetProperty) ||
// ((flags & BindingFlags.SetProperty) == BindingFlags.SetProperty))
// {
// return (bindingType.GetProperty(name, srchFlags) != null);
// }
// if (((flags & BindingFlags.GetField) == BindingFlags.GetField) ||
// ((flags & BindingFlags.SetField) == BindingFlags.SetField))
// {
// return (bindingType.GetField(name, srchFlags) != null);
// }
// if ((flags & BindingFlags.InvokeMethod) == BindingFlags.InvokeMethod)
// return (bindingType.GetMethod(name, srchFlags) != null);
// return false;
//}
}
}
| |
using System;
using System.Globalization;
using Should;
using NUnit.Framework;
namespace AutoMapper.UnitTests
{
namespace CustomFormatters
{
public class When_applying_global_formatting_rules : AutoMapperSpecBase
{
private ModelDto _modelDto;
public class HardEncoder : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
return string.Format("Hard {0}", context.SourceValue);
}
}
public class SoftEncoder : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
return string.Format("{0} {1} Soft", context.SourceValue, context.MemberName);
}
}
public class RokkenEncoder : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
return string.Format("{0} Rokken", context.SourceValue);
}
}
public class ModelDto
{
public string Value { get; set; }
}
public class ModelObject
{
public int Value { get; set; }
}
protected override void Establish_context()
{
Mapper.AddFormatter<HardEncoder>();
Mapper.AddFormatter(new SoftEncoder());
Mapper.AddFormatter(typeof(RokkenEncoder));
Mapper.AddFormatExpression(context => context.SourceValue + " Medium");
Mapper.CreateMap<ModelObject, ModelDto>();
var modelObject = new ModelObject { Value = 14 };
_modelDto = Mapper.Map<ModelObject, ModelDto>(modelObject);
}
[Test]
public void It_formats_the_values_in_the_order_declared()
{
_modelDto.Value.ShouldEqual("Hard 14 Value Soft Rokken Medium");
}
}
public class When_applying_type_specific_global_formatting_rules : AutoMapperSpecBase
{
private ModelDto _result;
private string _intResult;
public class ModelDto
{
public string StartDate { get; set; }
public string OtherValue { get; set; }
}
public class ModelObject
{
public DateTime StartDate { get; set; }
public int OtherValue { get; set; }
}
public class ShortDateFormatter : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
return ((DateTime)context.SourceValue).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
}
}
protected override void Establish_context()
{
Mapper.Initialize(cfg =>
{
cfg.ForSourceType<DateTime>().AddFormatter<ShortDateFormatter>();
cfg.ForSourceType<int>().AddFormatExpression(context => ((int)context.SourceValue + 1).ToString());
cfg.CreateMap<ModelObject, ModelDto>();
});
var model = new ModelObject { StartDate = new DateTime(2004, 12, 25), OtherValue = 43 };
_result = Mapper.Map<ModelObject, ModelDto>(model);
_intResult = Mapper.Map<int, string>(44);
}
[Test]
public void Should_format_using_concrete_formatter_class()
{
_result.StartDate.ShouldEqual("12/25/2004");
}
[Test]
public void Should_format_using_custom_expression_formatter()
{
_result.OtherValue.ShouldEqual("44");
}
[Test]
public void Should_use_formatter_outside_of_type_map()
{
_intResult.ShouldEqual("45");
}
}
public class When_applying_type_specific_and_general_global_formatting_rules : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelDto
{
public string OtherValue { get; set; }
}
public class ModelObject
{
public int OtherValue { get; set; }
}
protected override void Establish_context()
{
Mapper.AddFormatExpression(context => string.Format("{0} Value", context.SourceValue));
Mapper.ForSourceType<int>().AddFormatExpression(context => ((int)context.SourceValue + 1).ToString());
Mapper.CreateMap<ModelObject, ModelDto>();
var model = new ModelObject { OtherValue = 43 };
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_apply_the_type_specific_formatting_first_then_global_formatting()
{
_result.OtherValue.ShouldEqual("44 Value");
}
}
public class When_resetting_the_global_formatting : AutoMapperSpecBase
{
private ModelDto _modelDto;
public class CrazyEncoder : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
return "Crazy!!!";
}
}
public class ModelDto
{
public string Value { get; set; }
}
public class ModelObject
{
public int Value { get; set; }
}
protected override void Establish_context()
{
Mapper.AddFormatter<CrazyEncoder>();
Mapper.Reset();
Mapper.CreateMap<ModelObject, ModelDto>();
var modelObject = new ModelObject { Value = 14 };
_modelDto = Mapper.Map<ModelObject, ModelDto>(modelObject);
}
[Test]
public void Should_not_apply_the_global_formatting()
{
_modelDto.Value.ShouldEqual("14");
}
}
public class When_skipping_a_specific_property_formatting : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public int ValueOne { get; set; }
public int ValueTwo { get; set; }
}
public class ModelDto
{
public string ValueOne { get; set; }
public string ValueTwo { get; set; }
}
public class SampleFormatter : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
return "Value " + context.SourceValue;
}
}
protected override void Establish_context()
{
Mapper.ForSourceType<int>().AddFormatter<SampleFormatter>();
Mapper
.CreateMap<ModelObject, ModelDto>()
.ForMember(d => d.ValueTwo, opt => opt.SkipFormatter<SampleFormatter>());
var model = new ModelObject { ValueOne = 24, ValueTwo = 42 };
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_preserve_the_existing_formatter()
{
_result.ValueOne.ShouldEqual("Value 24");
}
[Test]
public void Should_not_format_using_the_skipped_formatter()
{
_result.ValueTwo.ShouldEqual("42");
}
}
public class When_skipping_a_specific_type_formatting : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public int ValueOne { get; set; }
}
public class ModelDto
{
public string ValueOne { get; set; }
}
public class SampleFormatter : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
return "Value " + context.SourceValue;
}
}
protected override void Establish_context()
{
Mapper.AddFormatter<SampleFormatter>();
Mapper.ForSourceType<int>().SkipFormatter<SampleFormatter>();
Mapper.CreateMap<ModelObject, ModelDto>();
var model = new ModelObject { ValueOne = 24 };
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_not_apply_the_skipped_formatting()
{
_result.ValueOne.ShouldEqual("24");
}
}
public class When_configuring_formatting_for_a_specific_member : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public int ValueOne { get; set; }
}
public class ModelDto
{
public string ValueOne { get; set; }
}
public class SampleFormatter : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
return "Value " + context.SourceValue;
}
}
protected override void Establish_context()
{
Mapper
.CreateMap<ModelObject, ModelDto>()
.ForMember(dto => dto.ValueOne, opt => opt.AddFormatter<SampleFormatter>());
var model = new ModelObject { ValueOne = 24 };
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_apply_formatting_to_that_member()
{
_result.ValueOne.ShouldEqual("Value 24");
}
}
public class When_substituting_a_specific_value_for_nulls : AutoMapperSpecBase
{
private ModelDto _result;
public class ModelObject
{
public string ValueOne { get; set; }
}
public class ModelDto
{
public string ValueOne { get; set; }
}
protected override void Establish_context()
{
Mapper
.CreateMap<ModelObject, ModelDto>()
.ForMember(dto => dto.ValueOne, opt => opt.NullSubstitute("I am null"));
var model = new ModelObject { ValueOne = null };
_result = Mapper.Map<ModelObject, ModelDto>(model);
}
[Test]
public void Should_replace_the_null_value_with_the_substitute()
{
_result.ValueOne.ShouldEqual("I am null");
}
}
public class When_using_a_custom_contruction_method_for_formatters : AutoMapperSpecBase
{
private Dest _result;
public class Source { public int Value { get; set; } }
public class Dest { public string Value { get; set; } }
public class CustomFormatter : IValueFormatter
{
private int _toAdd;
public CustomFormatter()
{
_toAdd = 7;
}
public CustomFormatter(int toAdd)
{
_toAdd = toAdd;
}
public string FormatValue(ResolutionContext context)
{
return (((int) context.SourceValue) + _toAdd).ToString();
}
}
public class OtherCustomFormatter : IValueFormatter
{
private string _toAppend;
public OtherCustomFormatter()
{
_toAppend = " Blarg";
}
public OtherCustomFormatter(string toAppend)
{
_toAppend = toAppend;
}
public string FormatValue(ResolutionContext context)
{
return context.SourceValue + _toAppend;
}
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Dest>();
Mapper.AddFormatter<CustomFormatter>().ConstructedBy(() => new CustomFormatter(10));
Mapper.AddFormatter(typeof(OtherCustomFormatter)).ConstructedBy(() => new OtherCustomFormatter(" Splorg"));
}
protected override void Because_of()
{
var source = new Source { Value = 10};
_result = Mapper.Map<Source, Dest>(source);
}
[Test]
public void Should_apply_the_constructor_specified()
{
_result.Value.ShouldEqual("20 Splorg");
}
}
public class When_using_a_global_custom_construction_method_for_formatters : AutoMapperSpecBase
{
private Destination _result;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public string Value { get; set; }
}
public class SomeFormatter : IValueFormatter
{
private readonly string _prefix = "asdf";
public SomeFormatter() {}
public SomeFormatter(string prefix)
{
_prefix = prefix;
}
public string FormatValue(ResolutionContext context)
{
return _prefix + context.SourceValue;
}
}
protected override void Establish_context()
{
Mapper.Initialize(cfg => cfg.ConstructServicesUsing(type => new SomeFormatter("ctor'd")));
Mapper.CreateMap<Source, Destination>()
.ForMember(d => d.Value, opt => opt.AddFormatter<SomeFormatter>());
}
protected override void Because_of()
{
_result = Mapper.Map<Source, Destination>(new Source {Value = 5});
}
[Test]
public void Should_use_the_global_construction_method_for_creation()
{
_result.Value.ShouldEqual("ctor'd5");
}
}
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NodaTime.Annotations;
using NodaTime.TimeZones.IO;
using NodaTime.Utility;
using JetBrains.Annotations;
namespace NodaTime.TimeZones
{
/// <summary>
/// Most time zones have a relatively small set of transitions at their start until they finally
/// settle down to either a fixed time zone or a daylight savings time zone. This provides the
/// container for the initial zone intervals and a pointer to the time zone that handles all of
/// the rest until the end of time.
/// </summary>
internal sealed class PrecalculatedDateTimeZone : DateTimeZone
{
private readonly ZoneInterval[] periods;
private readonly IZoneIntervalMapWithMinMax tailZone;
/// <summary>
/// The first instant covered by the tail zone, or Instant.AfterMaxValue if there's no tail zone.
/// </summary>
private readonly Instant tailZoneStart;
private readonly ZoneInterval firstTailZoneInterval;
/// <summary>
/// Initializes a new instance of the <see cref="PrecalculatedDateTimeZone"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="intervals">The intervals before the tail zone.</param>
/// <param name="tailZone">The tail zone - which can be any IZoneIntervalMap for normal operation,
/// but must be a StandardDaylightAlternatingMap if the result is to be serialized.</param>
[VisibleForTesting]
internal PrecalculatedDateTimeZone([NotNull] string id, [NotNull] ZoneInterval[] intervals, IZoneIntervalMapWithMinMax tailZone)
: base(id, false,
ComputeOffset(intervals, tailZone, Offset.Min),
ComputeOffset(intervals, tailZone, Offset.Max))
{
this.tailZone = tailZone;
this.periods = intervals;
this.tailZone = tailZone;
this.tailZoneStart = intervals[intervals.Length - 1].RawEnd; // We want this to be AfterMaxValue for tail-less zones.
if (tailZone != null)
{
// Cache a "clamped" zone interval for use at the start of the tail zone.
firstTailZoneInterval = tailZone.GetZoneInterval(tailZoneStart).WithStart(tailZoneStart);
}
ValidatePeriods(intervals, tailZone);
}
/// <summary>
/// Validates that all the periods before the tail zone make sense. We have to start at the beginning of time,
/// and then have adjoining periods. This is only called in the constructors.
/// </summary>
/// <remarks>This is only called from the constructors, but is internal to make it easier to test.</remarks>
/// <exception cref="ArgumentException">The periods specified are invalid.</exception>
internal static void ValidatePeriods(ZoneInterval[] periods, IZoneIntervalMap tailZone)
{
Preconditions.CheckArgument(periods.Length > 0, nameof(periods), "No periods specified in precalculated time zone");
Preconditions.CheckArgument(!periods[0].HasStart, nameof(periods), "Periods in precalculated time zone must start with the beginning of time");
for (int i = 0; i < periods.Length - 1; i++)
{
// Safe to use End here: there can't be a period *after* an endless one. Likewise it's safe to use Start on the next
// period, as there can't be a period *before* one which goes back to the start of time.
Preconditions.CheckArgument(periods[i].End == periods[i + 1].Start, nameof(periods), "Non-adjoining ZoneIntervals for precalculated time zone");
}
Preconditions.CheckArgument(tailZone != null || periods[periods.Length - 1].RawEnd == Instant.AfterMaxValue, nameof(tailZone), "Null tail zone given but periods don't cover all of time");
}
/// <summary>
/// Gets the zone offset period for the given instant.
/// </summary>
/// <param name="instant">The Instant to find.</param>
/// <returns>The ZoneInterval including the given instant.</returns>
public override ZoneInterval GetZoneInterval(Instant instant)
{
if (tailZone != null && instant >= tailZoneStart)
{
// Clamp the tail zone interval to start at the end of our final period, if necessary, so that the
// join is seamless.
ZoneInterval intervalFromTailZone = tailZone.GetZoneInterval(instant);
return intervalFromTailZone.RawStart < tailZoneStart ? firstTailZoneInterval : intervalFromTailZone;
}
int lower = 0; // Inclusive
int upper = periods.Length; // Exclusive
while (lower < upper)
{
int current = (lower + upper) / 2;
var candidate = periods[current];
if (candidate.RawStart > instant)
{
upper = current;
}
// Safe to use RawEnd, as it's just for the comparison.
else if (candidate.RawEnd <= instant)
{
lower = current + 1;
}
else
{
return candidate;
}
}
// Note: this would indicate a bug. The time zone is meant to cover the whole of time.
throw new InvalidOperationException($"Instant {instant} did not exist in time zone {Id}");
}
// TODO(2.0): Revisit this, given that it's useless at the moment.
/// <summary>
/// Returns true if this time zone is worth caching. Small time zones or time zones with
/// lots of quick changes do not work well with <see cref="CachedDateTimeZone"/>.
/// </summary>
/// <returns><c>true</c> if this instance is cachable; otherwise, <c>false</c>.</returns>
public bool IsCachable() =>
// TODO: Work out some decent rules for this. Previously we would only cache if the
// tail zone was non-null... which was *always* the case due to the use of NullDateTimeZone.
// We could potentially go back to returning tailZone != null - benchmarking required.
true;
public DateTimeZone MaybeCreateCachedZone()
{
return IsCachable() ? CachedDateTimeZone.ForZone(this) : this;
}
#region I/O
/// <summary>
/// Writes the time zone to the specified writer.
/// </summary>
/// <param name="writer">The writer to write to.</param>
internal void Write([NotNull] IDateTimeZoneWriter writer)
{
Preconditions.CheckNotNull(writer, nameof(writer));
// We used to create a pool of strings just for this zone. This was more efficient
// for some zones, as it meant that each string would be written out with just a single
// byte after the pooling. Optimizing the string pool globally instead allows for
// roughly the same efficiency, and simpler code here.
writer.WriteCount(periods.Length);
Instant? previous = null;
foreach (var period in periods)
{
writer.WriteZoneIntervalTransition(previous, (Instant) (previous = period.RawStart));
writer.WriteString(period.Name);
writer.WriteOffset(period.WallOffset);
writer.WriteOffset(period.Savings);
}
writer.WriteZoneIntervalTransition(previous, tailZoneStart);
// We could just check whether we've got to the end of the stream, but this
// feels slightly safer.
writer.WriteByte((byte) (tailZone == null ? 0 : 1));
if (tailZone != null)
{
// This is the only kind of zone we support in the new format. Enforce that...
var tailDstZone = (StandardDaylightAlternatingMap)tailZone;
tailDstZone.Write(writer);
}
}
/// <summary>
/// Reads a time zone from the specified reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="id">The id.</param>
/// <returns>The time zone.</returns>
internal static DateTimeZone Read([Trusted] [NotNull] IDateTimeZoneReader reader, [Trusted] [NotNull] string id)
{
Preconditions.DebugCheckNotNull(reader, nameof(reader));
Preconditions.DebugCheckNotNull(id, nameof(id));
int size = reader.ReadCount();
var periods = new ZoneInterval[size];
// It's not entirely clear why we don't just assume that the first zone interval always starts at Instant.BeforeMinValue
// (given that we check that later) but we don't... and changing that now could cause compatibility issues.
var start = reader.ReadZoneIntervalTransition(null);
for (int i = 0; i < size; i++)
{
var name = reader.ReadString();
var offset = reader.ReadOffset();
var savings = reader.ReadOffset();
var nextStart = reader.ReadZoneIntervalTransition(start);
periods[i] = new ZoneInterval(name, start, nextStart, offset, savings);
start = nextStart;
}
var tailZone = reader.ReadByte() == 1 ? StandardDaylightAlternatingMap.Read(reader) : null;
return new PrecalculatedDateTimeZone(id, periods, tailZone);
}
#endregion // I/O
#region Offset computation for constructors
// Essentially Func<Offset, Offset, Offset>
private delegate Offset OffsetAggregator(Offset x, Offset y);
private delegate Offset OffsetExtractor<in T>(T input);
// Reasonably simple way of computing the maximum/minimum offset
// from either periods or transitions, with or without a tail zone.
private static Offset ComputeOffset([NotNull] ZoneInterval[] intervals,
IZoneIntervalMapWithMinMax tailZone,
OffsetAggregator aggregator)
{
Preconditions.CheckNotNull(intervals, nameof(intervals));
Preconditions.CheckArgument(intervals.Length > 0, nameof(intervals), "No intervals specified");
Offset ret = intervals[0].WallOffset;
for (int i = 1; i < intervals.Length; i++)
{
ret = aggregator(ret, intervals[i].WallOffset);
}
if (tailZone != null)
{
// Effectively a shortcut for picking either tailZone.MinOffset or
// tailZone.MaxOffset
Offset bestFromZone = aggregator(tailZone.MinOffset, tailZone.MaxOffset);
ret = aggregator(ret, bestFromZone);
}
return ret;
}
#endregion
protected override bool EqualsImpl(DateTimeZone zone)
{
PrecalculatedDateTimeZone otherZone = (PrecalculatedDateTimeZone)zone;
// Check the individual fields first...
if (Id != otherZone.Id ||
!Equals(tailZone, otherZone.tailZone) ||
tailZoneStart != otherZone.tailZoneStart ||
!Equals(firstTailZoneInterval, otherZone.firstTailZoneInterval))
{
return false;
}
// Now all the intervals
if (periods.Length != otherZone.periods.Length)
{
return false;
}
for (int i = 0; i < periods.Length; i++)
{
if (!periods[i].Equals(otherZone.periods[i]))
{
return false;
}
}
return true;
}
public override int GetHashCode()
{
var hash = HashCodeHelper.Initialize().Hash(Id).Hash(tailZoneStart).Hash(firstTailZoneInterval).Hash(tailZone);
foreach (var period in periods)
{
hash = hash.Hash(period);
}
return hash.Value;
}
}
}
| |
#nullable disable
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Xml;
using WWT.Tours;
namespace WWT.Providers
{
public abstract partial class GetTourList : RequestProvider
{
private readonly WwtOptions _options;
public GetTourList(WwtOptions options)
{
_options = options;
}
protected abstract string SqlCommandString { get; }
protected abstract string HierarchySqlCommand { get; }
private int GetSqlToursVersion()
{
string strErrorMsg;
int version = -1;
strErrorMsg = "";
SqlConnection myConnection5 = new SqlConnection(_options.WwtToursDBConnectionString);
try
{
myConnection5.Open();
SqlCommand cmd = null;
cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 20;
cmd.Connection = myConnection5;
cmd.CommandText = "spGetTourVersion";
System.Data.SqlClient.SqlDataReader mySqlReader;
mySqlReader = cmd.ExecuteReader();
mySqlReader.Read();
int ordVersionNumber = mySqlReader.GetOrdinal("VersionNumber");
version = mySqlReader.GetInt32(ordVersionNumber);
}
catch (Exception ex)
{
//throw ex.GetBaseException();
strErrorMsg = ex.Message;
}
finally
{
if (myConnection5.State == ConnectionState.Open)
myConnection5.Close();
}
return version;
}
protected virtual void LoadTourFromRow(DataRow dr, Tour tour)
{
}
private int GetSQLTourArrayList(List<Tour> sqlTours, string query)
{
StoredProc sp = new StoredProc(query, _options.WwtToursDBConnectionString);
DataTable dt = new DataTable();
int nRet = sp.RunQuery(dt);
sp.Dispose();
foreach (DataRow dr in dt.Rows)
{
Tour tr = new Tour();
tr.TourTitle = Convert.ToString(dr["TourTitle"]);
tr.TourGuid = new Guid(dr["TourGUID"].ToString());
tr.TourDescription = Convert.ToString(dr["TourDescription"]);
tr.AuthorEmailAddress = Convert.ToString(dr["AuthorEmailAddress"]);
tr.AuthorName = Convert.ToString(dr["AuthorName"]);
tr.AuthorURL = Convert.ToString(dr["AuthorURL"]);
tr.AverageRating = Convert.ToDouble(dr["AverageRating"]);
tr.LengthInSecs = Convert.ToInt32(dr["LengthInSecs"]);
tr.OrganizationURL = Convert.ToString(dr["OrganizationURL"]);
tr.OrganizationName = Convert.ToString(dr["OrganizationName"]);
LoadTourFromRow(dr, tr);
sqlTours.Add(tr);
}
return 0;
}
protected virtual void WriteTour(XmlWriter xmlWriter, Tour tr)
{
}
private void AddToursToChildNode(XmlWriter xmlWriter, int parcatId)
{
List<Tour> sqlTours = new List<Tour>();
int nRet = GetSQLTourArrayList(sqlTours, "exec spGetWWTToursForDateRangeFromCatId " + parcatId + ", null, null, 0");
foreach (Tour tr in sqlTours)
{
xmlWriter.WriteStartElement("Tour");
xmlWriter.WriteAttributeString("Title", tr.TourTitle);
xmlWriter.WriteAttributeString("ID", tr.TourGuid.ToString());
xmlWriter.WriteAttributeString("Description", tr.TourDescription);
xmlWriter.WriteAttributeString("Classification", "Other");
xmlWriter.WriteAttributeString("AuthorEmail", tr.AuthorEmailAddress);
xmlWriter.WriteAttributeString("Author", tr.AuthorName);
xmlWriter.WriteAttributeString("AuthorUrl", tr.AuthorURL);
xmlWriter.WriteAttributeString("AverageRating", tr.AverageRating.ToString());
xmlWriter.WriteAttributeString("LengthInSecs", tr.LengthInSecs.ToString());
xmlWriter.WriteAttributeString("OrganizationUrl", tr.OrganizationURL);
xmlWriter.WriteAttributeString("OrganizationName", tr.OrganizationName);
WriteTour(xmlWriter, tr);
xmlWriter.WriteEndElement();
}
StoredProc sp1 = new StoredProc(SqlCommandString + parcatId.ToString(), _options.WwtToursDBConnectionString);
DataTable dt = new DataTable();
int nRet1 = sp1.RunQuery(dt);
sp1.Dispose();
foreach (DataRow dr in dt.Rows)
{
int tempcatId = Convert.ToInt32(dr[0]);
int tempparcatId = Convert.ToInt32(dr[1]);
string catName = Convert.ToString(dr[2]);
string catTnUrl = Convert.ToString(dr[3]);
xmlWriter.WriteStartElement("Folder");
xmlWriter.WriteAttributeString("Name", catName);
xmlWriter.WriteAttributeString("Group", "Tour");
xmlWriter.WriteAttributeString("Thumbnail", catTnUrl);
AddToursToChildNode(xmlWriter, tempcatId);
xmlWriter.WriteEndElement();
}
}
private string LoadTourHierarchy()
{
List<Tour> sqlTours = new List<Tour>();
int nRet = GetSQLTourArrayList(sqlTours, "exec spGetWWTToursForDateRangeFromCatId 0, null, null, 0");
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(sw))
{
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
xmlWriter.WriteStartElement("Folder");
if (sqlTours.Count > 0)
{
foreach (Tour tr in sqlTours)
{
xmlWriter.WriteStartElement("Tour");
xmlWriter.WriteAttributeString("Title", tr.TourTitle);
xmlWriter.WriteAttributeString("ID", tr.TourGuid.ToString());
xmlWriter.WriteAttributeString("Description", tr.TourDescription);
xmlWriter.WriteAttributeString("Classification", "Other");
xmlWriter.WriteAttributeString("AuthorEmail", tr.AuthorEmailAddress);
xmlWriter.WriteAttributeString("Author", tr.AuthorName);
xmlWriter.WriteAttributeString("AuthorUrl", tr.AuthorURL);
xmlWriter.WriteAttributeString("AverageRating", tr.AverageRating.ToString());
xmlWriter.WriteAttributeString("LengthInSecs", tr.LengthInSecs.ToString());
xmlWriter.WriteAttributeString("OrganizationUrl", tr.OrganizationURL);
xmlWriter.WriteAttributeString("OrganizationName", tr.OrganizationName);
WriteTour(xmlWriter, tr);
xmlWriter.WriteEndElement();
}
}
StoredProc sp1 = new StoredProc(HierarchySqlCommand, _options.WwtToursDBConnectionString);
DataTable dt = new DataTable();
int nRet1 = sp1.RunQuery(dt);
sp1.Dispose();
foreach (DataRow dr in dt.Rows)
{
int catId = Convert.ToInt32(dr[0]);
int parcatId = Convert.ToInt32(dr[1]);
string catName = Convert.ToString(dr[2]);
string catTnUrl = Convert.ToString(dr[3]);
xmlWriter.WriteStartElement("Folder");
xmlWriter.WriteAttributeString("Name", catName);
xmlWriter.WriteAttributeString("Group", "Tour");
xmlWriter.WriteAttributeString("Thumbnail", catTnUrl);
AddToursToChildNode(xmlWriter, catId);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
xmlWriter.Close();
}
sw.Close();
return sw.ToString();
//StreamWriter fsw = new StreamWriter(@"c:\\test_Tour.xml");
//fsw.WriteLine(sw.ToString());
//fsw.Close();
}
}
protected int UpdateCacheEx(ICache cache)
{
bool needToBuild;
int fromCacheVersion;
int fromSqlVersion;
int minutesToAdd;
List<Tour> sqlTours = new List<Tour>();
needToBuild = false;
DateTime fromCacheDateTime;
if (cache.Get("WWTXMLTours") == null)
{
needToBuild = true;
}
// see if you need to build the cache....
// if it has been more than n minutes since you last checked the version, then
// get the version number from sql. if different, then needtoupdate.
try
{
fromCacheDateTime = (DateTime)cache.Get("LastCacheUpdateDateTime");
}
catch
{
fromCacheDateTime = System.DateTime.Now.AddDays(-1);
}
minutesToAdd = _options.TourVersionCheckIntervalMinutes;
if (System.DateTime.Now > fromCacheDateTime.AddMinutes(minutesToAdd))
{
try
{
fromCacheVersion = (int)cache.Get("Version");
}
catch
{
fromCacheVersion = 0;
}
if (fromCacheVersion == 0)
{
needToBuild = true;
}
else
{
fromSqlVersion = GetSqlToursVersion();
needToBuild = true;
if (fromSqlVersion != fromCacheVersion)
{
needToBuild = true;
}
}
}
if (needToBuild)
{
cache.Remove("LastCacheUpdateDateTime");
cache.Add("LastCacheUpdateDateTime", System.DateTime.Now, DateTime.MaxValue, new TimeSpan(24, 0, 0));
//update the version number in the cache (datetime is already updated)
fromSqlVersion = GetSqlToursVersion();
cache.Remove("Version");
cache.Add("Version", fromSqlVersion, DateTime.MaxValue, new TimeSpan(24, 0, 0));
//update the WWTTours cache with the SQLTours ArrayList
cache.Remove("WWTXMLTours");
cache.Add("WWTXMLTours", LoadTourHierarchy(), DateTime.MaxValue, new TimeSpan(24, 0, 0));
}
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Fabric;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace SewingMachine.Impl
{
class Invoker
{
// write
public readonly Action<KeyValueStoreReplica, TransactionBase, IntPtr, int, IntPtr> Add;
public readonly Func<KeyValueStoreReplica, TransactionBase, IntPtr, sbyte> Contains;
public readonly Func<KeyValueStoreReplica, TransactionBase, IntPtr, sbyte, object> EnumerateByKey2;
public readonly Func<IEnumerator<KeyValueStoreNotification>, object> GetNativeNotificationEnumerator2;
public readonly Func<object, Func<RawItem, object>, object> NativeEnumeratorGetCurrent;
public readonly Func<object, sbyte> NativeEnumeratorTryMoveNext;
public readonly Func<object, Func<RawItem, object>, object> NativeNotificationEnumeratorGetCurrent;
public readonly Func<object, sbyte> NativeNotificationEnumeratorTryMoveNext;
public readonly Action<KeyValueStoreReplica, TransactionBase, IntPtr, long> Remove;
public readonly Func<KeyValueStoreReplica, TransactionBase, IntPtr, int, IntPtr, sbyte> TryAdd;
public readonly Func<KeyValueStoreReplica, TransactionBase, IntPtr, Func<RawItem, object>, object> TryGet;
public readonly Func<KeyValueStoreReplica, TransactionBase, IntPtr, long, sbyte> TryRemove;
public readonly Func<KeyValueStoreReplica, TransactionBase, IntPtr, int, IntPtr, long, sbyte> TryUpdate;
public readonly Action<KeyValueStoreReplica, TransactionBase, IntPtr, int, IntPtr, long> Update;
public Invoker()
{
var methods = InternalFabric.NativeReplicaType.GetMethods().ToDictionary(mi => mi.Name);
// Add
// replica, tx, key, lenght, value
Add = Utils.Build<Action<KeyValueStoreReplica, TransactionBase, IntPtr, int, IntPtr>>(methods["Add"],
EmitNonreadingMethod);
TryAdd =
Utils.Build<Func<KeyValueStoreReplica, TransactionBase, IntPtr, int, IntPtr, sbyte>>(
methods["TryAdd"], EmitNonreadingMethod);
// Update
// replica, tx, key, lenght, value, sequenceNumber
Update =
Utils.Build<Action<KeyValueStoreReplica, TransactionBase, IntPtr, int, IntPtr, long>>(
methods["Update"], EmitNonreadingMethod);
TryUpdate =
Utils.Build<Func<KeyValueStoreReplica, TransactionBase, IntPtr, int, IntPtr, long, sbyte>>(
methods["TryUpdate"], EmitNonreadingMethod);
// Remove
// replica, tx, key, sequenceNumber
Remove = Utils.Build<Action<KeyValueStoreReplica, TransactionBase, IntPtr, long>>(methods["Remove"],
EmitNonreadingMethod);
TryRemove =
Utils.Build<Func<KeyValueStoreReplica, TransactionBase, IntPtr, long, sbyte>>(methods["TryRemove"],
EmitNonreadingMethod);
// Contains
Contains = Utils.Build<Func<KeyValueStoreReplica, TransactionBase, IntPtr, sbyte>>(methods["Contains"],
EmitNonreadingMethod);
// TryGetValue
var mapFromNativeToObject = BuildMappingFromNativeResultToObject();
TryGet = BuildTryGet(methods["TryGet"], mapFromNativeToObject);
// EnumerateByKey2
EnumerateByKey2 =
Utils.Build<Func<KeyValueStoreReplica, TransactionBase, IntPtr, sbyte, object>>(
methods["EnumerateByKey2"], EmitNonreadingMethod);
// NativeEnumeratorMoveNext
var enumerator =
InternalFabric.NativeRuntimeType.DeclaredNestedTypes.Single(
t => t.Name == "IFabricKeyValueStoreItemEnumerator2");
var enumeratorMethods = enumerator.GetMethods().ToDictionary(mi => mi.Name);
NativeEnumeratorTryMoveNext = Utils.Build<Func<object, sbyte>>(enumeratorMethods["TryMoveNext"],
(mi, il, parameterTypes) =>
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, enumerator);
il.EmitCall(OpCodes.Callvirt, mi, null);
il.Emit(OpCodes.Ret);
});
NativeEnumeratorGetCurrent =
Utils.Build<Func<object, Func<RawItem, object>, object>>(enumeratorMethods["get_Current"],
(mi, il, parameterTypes) =>
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, enumerator);
il.EmitCall(OpCodes.Callvirt, mi, null); // stack: IFabricKeyValueStoreItemResult
il.Emit(OpCodes.Ldarg_1); // stack: IFabricKeyValueStoreItemResult, mapper
il.EmitCall(OpCodes.Call, mapFromNativeToObject, null); // stack: object
il.Emit(OpCodes.Ret);
});
// KeyValueStoreNotificationEnumerator
var notificationEnumerator =
typeof(KeyValueStoreNotification).Assembly.GetType(
"System.Fabric.KeyValueStoreNotificationEnumerator");
var nativeNotificationEnumeratorField = notificationEnumerator.GetField("nativeEnumerator",
ReflectionHelpers.AllInstance);
var nativeNotificationEnumeratorType = nativeNotificationEnumeratorField.FieldType;
GetNativeNotificationEnumerator2 =
Utils.Build<Func<IEnumerator<KeyValueStoreNotification>, object>>(
"dm_getNativeNotificationEnumerator",
(il, types) =>
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, notificationEnumerator);
il.Emit(OpCodes.Ldfld, nativeNotificationEnumeratorField);
il.Emit(OpCodes.Ret);
});
NativeNotificationEnumeratorTryMoveNext =
Utils.Build<Func<object, sbyte>>(
nativeNotificationEnumeratorType.GetMethod("TryMoveNext", ReflectionHelpers.AllInstance),
(mi, il, types) =>
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, nativeNotificationEnumeratorType);
il.EmitCall(OpCodes.Callvirt, mi, null);
il.Emit(OpCodes.Ret);
});
NativeNotificationEnumeratorGetCurrent =
Utils.Build<Func<object, Func<RawItem, object>, object>>(
nativeNotificationEnumeratorType.GetMethod("get_Current"),
(mi, il, parameterTypes) =>
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, enumerator);
il.EmitCall(OpCodes.Callvirt, mi, null);
// stack: NativeRuntime.IFabricKeyValueStoreNotification
il.Emit(OpCodes.Ldarg_1); // stack: IFabricKeyValueStoreItemResult, mapper
il.EmitCall(OpCodes.Call, mapFromNativeToObject, null); // stack: object
il.Emit(OpCodes.Ret);
});
}
static void EmitNonreadingMethod(MethodInfo nativeMethod, ILGenerator il, Type[] parameterTypes)
{
LoadStoreTxAndKey(il);
var count = parameterTypes.Length;
if (count > 3)
il.Emit(OpCodes.Ldarg_3);
if (count > 4)
il.Emit(OpCodes.Ldarg_S, (byte) 4);
if (count > 5)
il.Emit(OpCodes.Ldarg_S, (byte) 5);
if (count > 6)
throw new NotImplementedException();
il.EmitCall(OpCodes.Callvirt, nativeMethod, null);
il.Emit(OpCodes.Ret);
}
static Func<KeyValueStoreReplica, TransactionBase, IntPtr, Func<RawItem, object>, object> BuildTryGet(
MethodInfo tryGetMethod, MethodInfo mapFromNativeToObject)
{
return
Utils.Build<Func<KeyValueStoreReplica, TransactionBase, IntPtr, Func<RawItem, object>, object>>(
tryGetMethod,
(mi, il, _) =>
{
il.DeclareLocal(InternalFabric.KeyValueStoreItemResultType); // 0, native result
il.DeclareLocal(InternalFabric.KeyValueStoreItemType.MakePointerType());
// 1, NativeTypes.FABRIC_KEY_VALUE_STORE_ITEM*
il.DeclareLocal(InternalFabric.KeyValueStoreItemMetadataType.MakePointerType());
// 2, NativeTypes.FABRIC_KEY_VALUE_STORE_ITEM_METADATA*
il.DeclareLocal(typeof(RawItem)); // 3, RawItem
LoadStoreTxAndKey(il);
il.EmitCall(OpCodes.Callvirt, mi, null);
il.Emit(OpCodes.Ldarg_3);
// nativeResult, func
il.EmitCall(OpCodes.Call, mapFromNativeToObject, null);
// object
il.Emit(OpCodes.Ret);
});
}
static DynamicMethod BuildMappingFromNativeResultToObject()
{
var method = new DynamicMethod("dm_MapFromNativeResultTypeToObject", typeof(object),
new[] {InternalFabric.KeyValueStoreItemResultType, typeof(Func<RawItem, object>)},
typeof(KeyValueStoreReplica).Module, true);
var il = method.GetILGenerator();
il.DeclareLocal(InternalFabric.KeyValueStoreItemResultType); // 0, native result
il.DeclareLocal(InternalFabric.KeyValueStoreItemType.MakePointerType());
// 1, NativeTypes.FABRIC_KEY_VALUE_STORE_ITEM*
il.DeclareLocal(InternalFabric.KeyValueStoreItemMetadataType.MakePointerType());
// 2, NativeTypes.FABRIC_KEY_VALUE_STORE_ITEM_METADATA*
il.DeclareLocal(typeof(RawItem)); // 3, RawItem
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Stloc_0);
var nonNullResult = il.DefineLabel();
// if (result == null)
//{
// return null;
//}
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Brtrue_S, nonNullResult);
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Ret);
il.MarkLabel(nonNullResult);
// GC.KeepAlive(result);
il.Emit(OpCodes.Ldloc_0);
il.EmitCall(OpCodes.Call, typeof(GC).GetMethod("KeepAlive"), null);
// nativeItemResult.get_Item()
il.Emit(OpCodes.Ldloc_0);
il.EmitCall(OpCodes.Callvirt, InternalFabric.KeyValueStoreItemResultType.GetMethod("get_Item"), null);
il.EmitCall(OpCodes.Call, ReflectionHelpers.CastIntPtrToVoidPtr, null);
il.Emit(OpCodes.Stloc_1);
// empty stack, processing metadata
il.Emit(OpCodes.Ldloc_1); // NativeTypes.FABRIC_KEY_VALUE_STORE_ITEM*
il.Emit(OpCodes.Ldfld, InternalFabric.KeyValueStoreItemType.GetField("Metadata")); // IntPtr
il.EmitCall(OpCodes.Call, ReflectionHelpers.CastIntPtrToVoidPtr, null); // void*
il.Emit(OpCodes.Stloc_2);
il.Emit(OpCodes.Ldloc_2); // NativeTypes.FABRIC_KEY_VALUE_STORE_ITEM_METADATA*
il.Emit(OpCodes.Ldfld, InternalFabric.KeyValueStoreItemMetadataType.GetField("Key")); // IntPtr
il.Emit(OpCodes.Ldloc_2); // IntPtr, NativeTypes.FABRIC_KEY_VALUE_STORE_ITEM_METADATA*
il.Emit(OpCodes.Ldfld, InternalFabric.KeyValueStoreItemMetadataType.GetField("ValueSizeInBytes"));
// IntPtr, int
il.Emit(OpCodes.Ldloc_2); // IntPtr, int, NativeTypes.FABRIC_KEY_VALUE_STORE_ITEM_METADATA*
il.Emit(OpCodes.Ldfld, InternalFabric.KeyValueStoreItemMetadataType.GetField("SequenceNumber"));
// IntPtr, int, long
il.Emit(OpCodes.Ldloc_1); // IntPtr, int, long, NativeTypes.FABRIC_KEY_VALUE_STORE_ITEM*
il.Emit(OpCodes.Ldfld, InternalFabric.KeyValueStoreItemType.GetField("Value"));
// IntPtr (char*), int, long, IntPtr (byte*)
// stack: IntPtr (char*), int, long, IntPtr (byte*)
var ctor = typeof(RawItem).GetConstructors().Single(c => c.GetParameters().Length == 4);
il.Emit(OpCodes.Newobj, ctor);
// stack: rawItem
il.Emit(OpCodes.Stloc_3);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldloc_3);
// stack: func, rawItem
il.EmitCall(OpCodes.Callvirt, typeof(Func<RawItem, object>).GetMethod("Invoke"), null);
// object
il.Emit(OpCodes.Ret);
return method;
}
static void LoadStoreTxAndKey(ILGenerator il)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, InternalFabric.NativeStoreField); // nativeStore
il.Emit(OpCodes.Ldarg_1); // nativeStore, tx
il.EmitCall(OpCodes.Callvirt, InternalFabric.GetNativeTx, null); // nativeStore, nativeTx
il.Emit(OpCodes.Ldarg_2); // nativeStore, nativeTx, key
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if WCF_SUPPORTED
namespace NLog.LogReceiverService
{
using System.ServiceModel.Description;
using System;
using System.ComponentModel;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
/// <summary>
/// Abstract base class for the WcfLogReceiverXXXWay classes. It can only be
/// used internally (see internal constructor). It passes off any Channel usage
/// to the inheriting class.
/// </summary>
/// <typeparam name="TService">Type of the WCF service.</typeparam>
public abstract class WcfLogReceiverClientBase<TService> : ClientBase<TService>, IWcfLogReceiverClient
where TService : class
{
/// <summary>
/// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class.
/// </summary>
protected WcfLogReceiverClientBase()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class.
/// </summary>
/// <param name="endpointConfigurationName">Name of the endpoint configuration.</param>
protected WcfLogReceiverClientBase(string endpointConfigurationName)
: base(endpointConfigurationName)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class.
/// </summary>
/// <param name="endpointConfigurationName">Name of the endpoint configuration.</param>
/// <param name="remoteAddress">The remote address.</param>
protected WcfLogReceiverClientBase(string endpointConfigurationName, string remoteAddress)
: base(endpointConfigurationName, remoteAddress)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class.
/// </summary>
/// <param name="endpointConfigurationName">Name of the endpoint configuration.</param>
/// <param name="remoteAddress">The remote address.</param>
protected WcfLogReceiverClientBase(string endpointConfigurationName, EndpointAddress remoteAddress)
: base(endpointConfigurationName, remoteAddress)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WcfLogReceiverClientBase{TService}"/> class.
/// </summary>
/// <param name="binding">The binding.</param>
/// <param name="remoteAddress">The remote address.</param>
protected WcfLogReceiverClientBase(Binding binding, EndpointAddress remoteAddress)
: base(binding, remoteAddress)
{
}
/// <summary>
/// Occurs when the log message processing has completed.
/// </summary>
public event EventHandler<AsyncCompletedEventArgs> ProcessLogMessagesCompleted;
/// <summary>
/// Occurs when Open operation has completed.
/// </summary>
public event EventHandler<AsyncCompletedEventArgs> OpenCompleted;
/// <summary>
/// Occurs when Close operation has completed.
/// </summary>
public event EventHandler<AsyncCompletedEventArgs> CloseCompleted;
#if !NET4_0 && !NET3_5 && !NETSTANDARD
/// <summary>
/// Gets or sets the cookie container.
/// </summary>
/// <value>The cookie container.</value>
public CookieContainer CookieContainer
{
get
{
var httpCookieContainerManager = InnerChannel.GetProperty<IHttpCookieContainerManager>();
return httpCookieContainerManager?.CookieContainer;
}
set
{
var httpCookieContainerManager = InnerChannel.GetProperty<IHttpCookieContainerManager>();
if (httpCookieContainerManager != null)
{
httpCookieContainerManager.CookieContainer = value;
}
else
{
throw new InvalidOperationException("Unable to set the CookieContainer. Please make sure the binding contains an HttpCookieContainerBindingElement.");
}
}
}
#endif
/// <summary>
/// Opens the client asynchronously.
/// </summary>
public void OpenAsync()
{
OpenAsync(null);
}
/// <summary>
/// Opens the client asynchronously.
/// </summary>
/// <param name="userState">User-specific state.</param>
public void OpenAsync(object userState)
{
InvokeAsync(OnBeginOpen, null, OnEndOpen, OnOpenCompleted, userState);
}
/// <summary>
/// Closes the client asynchronously.
/// </summary>
public void CloseAsync()
{
CloseAsync(null);
}
/// <summary>
/// Closes the client asynchronously.
/// </summary>
/// <param name="userState">User-specific state.</param>
public void CloseAsync(object userState)
{
InvokeAsync(OnBeginClose, null, OnEndClose, OnCloseCompleted, userState);
}
/// <summary>
/// Processes the log messages asynchronously.
/// </summary>
/// <param name="events">The events to send.</param>
public void ProcessLogMessagesAsync(NLogEvents events)
{
ProcessLogMessagesAsync(events, null);
}
/// <summary>
/// Processes the log messages asynchronously.
/// </summary>
/// <param name="events">The events to send.</param>
/// <param name="userState">User-specific state.</param>
public void ProcessLogMessagesAsync(NLogEvents events, object userState)
{
InvokeAsync(
OnBeginProcessLogMessages,
new object[] { events },
OnEndProcessLogMessages,
OnProcessLogMessagesCompleted,
userState);
}
/// <summary>
/// Begins processing of log messages.
/// </summary>
/// <param name="events">The events to send.</param>
/// <param name="callback">The callback.</param>
/// <param name="asyncState">Asynchronous state.</param>
/// <returns>
/// IAsyncResult value which can be passed to <see cref="ILogReceiverOneWayClient.EndProcessLogMessages"/>.
/// </returns>
public abstract IAsyncResult BeginProcessLogMessages(NLogEvents events, AsyncCallback callback, object asyncState);
/// <summary>
/// Ends asynchronous processing of log messages.
/// </summary>
/// <param name="result">The result.</param>
public abstract void EndProcessLogMessages(IAsyncResult result);
private IAsyncResult OnBeginProcessLogMessages(object[] inValues, AsyncCallback callback, object asyncState)
{
var events = (NLogEvents)inValues[0];
return BeginProcessLogMessages(events, callback, asyncState);
}
private object[] OnEndProcessLogMessages(IAsyncResult result)
{
EndProcessLogMessages(result);
return null;
}
private void OnProcessLogMessagesCompleted(object state)
{
if (ProcessLogMessagesCompleted != null)
{
var e = (InvokeAsyncCompletedEventArgs)state;
ProcessLogMessagesCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState));
}
}
private IAsyncResult OnBeginOpen(object[] inValues, AsyncCallback callback, object asyncState)
{
return ((ICommunicationObject)this).BeginOpen(callback, asyncState);
}
private object[] OnEndOpen(IAsyncResult result)
{
((ICommunicationObject)this).EndOpen(result);
return null;
}
private void OnOpenCompleted(object state)
{
if (OpenCompleted != null)
{
var e = (InvokeAsyncCompletedEventArgs)state;
OpenCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState));
}
}
private IAsyncResult OnBeginClose(object[] inValues, AsyncCallback callback, object asyncState)
{
return ((ICommunicationObject)this).BeginClose(callback, asyncState);
}
private object[] OnEndClose(IAsyncResult result)
{
((ICommunicationObject)this).EndClose(result);
return null;
}
private void OnCloseCompleted(object state)
{
if (CloseCompleted != null)
{
var e = (InvokeAsyncCompletedEventArgs)state;
CloseCompleted(this, new AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState));
}
}
}
}
#endif
| |
/////////////////////////////////////////////////////////////////////////////////
//
// vp_PlayerDamageHandler.cs
// ?VisionPunk. All Rights Reserved.
// https://twitter.com/VisionPunk
// http://www.visionpunk.com
//
// description: a version of the vp_DamageHandler class extended for use with
// vp_PlayerEventHandler
//
/////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class vp_PlayerDamageHandler : vp_DamageHandler
{
private vp_PlayerEventHandler m_Player = null; // should never be referenced directly
protected vp_PlayerEventHandler Player // lazy initialization of the event handler field
{
get
{
if (m_Player == null)
m_Player = transform.GetComponent<vp_PlayerEventHandler>();
return m_Player;
}
}
private vp_PlayerInventory m_Inventory = null;
protected vp_PlayerInventory Inventory
{
get
{
if (m_Inventory == null)
m_Inventory = transform.root.GetComponentInChildren<vp_PlayerInventory>();
return m_Inventory;
}
}
// falling damage
public bool AllowFallDamage = true;
public float FallImpactThreshold = .15f;
public bool DeathOnFallImpactThreshold = false;
public Vector2 FallImpactPitch = new Vector2(1.0f, 1.5f); // random pitch range for fall impact sounds
public List<AudioClip> FallImpactSounds = new List<AudioClip>();
protected float m_FallImpactMultiplier = 2;
protected bool m_InventoryWasEnabledAtStart = true; // helper feature to facilitate developing with a temp-disabled inventory
protected List<Collider> m_Colliders = null;
protected List<Collider> Colliders
{
get
{
if (m_Colliders == null)
{
m_Colliders = new List<Collider>();
foreach (Collider c in GetComponentsInChildren<Collider>())
{
if (c.gameObject.layer == vp_Layer.RemotePlayer)
{
m_Colliders.Add(c);
}
}
}
return m_Colliders;
}
}
/// <summary>
/// registers this component with the event handler (if any).
/// NOTE: this is overriden by vp_FPPlayerEventHandler
/// </summary>
protected override void OnEnable()
{
if (Player != null)
Player.Register(this);
}
/// <summary>
/// unregisters this component from the event handler (if any).
/// NOTE: this is overriden by vp_FPPlayerEventHandler
/// </summary>
protected override void OnDisable()
{
if (Player != null)
Player.Unregister(this);
}
/// <summary>
///
/// </summary>
void Start()
{
if (Inventory != null)
m_InventoryWasEnabledAtStart = Inventory.enabled;
}
/// <summary>
/// instantiates the player's death effect, clears the current
/// weapon and activates the Dead activity
/// </summary>
public override void Die()
{
if (!enabled || !vp_Utility.IsActive(gameObject))
return;
if (m_Audio != null)
{
m_Audio.pitch = Time.timeScale;
m_Audio.PlayOneShot(DeathSound);
}
foreach (GameObject o in DeathSpawnObjects)
{
if (o != null)
vp_Utility.Instantiate(o, transform.position, transform.rotation);
}
foreach (Collider c in Colliders)
{
c.enabled = false;
}
if ((Inventory != null) && Inventory.enabled)
Inventory.enabled = false;
Player.SetWeapon.Argument = 0;
Player.SetWeapon.Start();
Player.Dead.Start();
Player.Run.Stop();
Player.Jump.Stop();
Player.Crouch.Stop();
Player.Zoom.Stop();
Player.Attack.Stop();
Player.Reload.Stop();
Player.Climb.Stop();
Player.Interact.Stop();
// if we're the master in multiplayer, send kill event to other players
if (vp_Gameplay.isMultiplayer && vp_Gameplay.isMaster)
{
//Debug.Log("sending kill event from master scene to vp_MasterClient");
vp_GlobalEvent<Transform>.Send("TransmitKill", transform.root);
}
}
/// <summary>
///
/// </summary>
protected override void Reset()
{
base.Reset();
if (!Application.isPlaying)
return;
Player.Dead.Stop();
Player.Stop.Send();
foreach (Collider c in Colliders)
{
c.enabled = true;
}
if ((Inventory != null) && !Inventory.enabled)
Inventory.enabled = m_InventoryWasEnabledAtStart;
if (m_Audio != null)
{
m_Audio.pitch = Time.timeScale;
m_Audio.PlayOneShot(RespawnSound);
}
}
/// <summary>
/// gets or sets the current health
/// </summary>
protected virtual float OnValue_Health
{
get
{
return CurrentHealth;
}
set
{
CurrentHealth = Mathf.Min(value, MaxHealth); // health is not allowed to go above max, but negative health is allowed (for gibbing)
}
}
/// <summary>
/// gets the player's max health
/// </summary>
protected virtual float OnValue_MaxHealth
{
get
{
return MaxHealth;
}
}
/// <summary>
/// applies falling damage to the player
/// </summary>
protected virtual void OnMessage_FallImpact(float impact)
{
if (Player.Dead.Active || !AllowFallDamage || impact <= FallImpactThreshold)
return;
vp_AudioUtility.PlayRandomSound(m_Audio, FallImpactSounds, FallImpactPitch);
float damage = (float)Mathf.Abs((float)(DeathOnFallImpactThreshold ? MaxHealth : MaxHealth * impact));
Damage(new vp_DamageInfo(damage, transform, transform, vp_DamageInfo.DamageType.Fall));
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Server;
using Server.Items;
using Server.Misc;
using Server.Mobiles;
using Server.Network;
using Server.Spells;
using Server.Spells.Fifth;
using Server.Spells.Seventh;
using Server.Spells.Ninjitsu;
namespace Server
{
public class AOS
{
public static void DisableStatInfluences()
{
for( int i = 0; i < SkillInfo.Table.Length; ++i )
{
SkillInfo info = SkillInfo.Table[i];
info.StrScale = 0.0;
info.DexScale = 0.0;
info.IntScale = 0.0;
info.StatTotal = 0.0;
}
}
public static int Damage( Mobile m, int damage, bool ignoreArmor, int phys, int fire, int cold, int pois, int nrgy )
{
return Damage( m, null, damage, ignoreArmor, phys, fire, cold, pois, nrgy );
}
public static int Damage( Mobile m, int damage, int phys, int fire, int cold, int pois, int nrgy )
{
return Damage( m, null, damage, phys, fire, cold, pois, nrgy );
}
public static int Damage(Mobile m, Mobile from, int damage, int phys, int fire, int cold, int pois, int nrgy)
{
return Damage(m, from, damage, false, phys, fire, cold, pois, nrgy, 0, 0, false, false, false);
}
public static int Damage(Mobile m, Mobile from, int damage, int phys, int fire, int cold, int pois, int nrgy, int chaos)
{
return Damage(m, from, damage, false, phys, fire, cold, pois, nrgy, chaos, 0, false, false, false);
}
public static int Damage(Mobile m, Mobile from, int damage, bool ignoreArmor, int phys, int fire, int cold, int pois, int nrgy)
{
return Damage(m, from, damage, ignoreArmor, phys, fire, cold, pois, nrgy, 0, 0, false, false, false);
}
public static int Damage(Mobile m, Mobile from, int damage, int phys, int fire, int cold, int pois, int nrgy, bool keepAlive)
{
return Damage(m, from, damage, false, phys, fire, cold, pois, nrgy, 0, 0, keepAlive, false, false);
}
public static int Damage(Mobile m, Mobile from, int damage, bool ignoreArmor, int phys, int fire, int cold, int pois, int nrgy, int chaos, int direct, bool keepAlive, bool archer, bool deathStrike)
{
if( m == null || m.Deleted || !m.Alive || damage <= 0 )
return 0;
if( phys == 0 && fire == 100 && cold == 0 && pois == 0 && nrgy == 0 )
Mobiles.MeerMage.StopEffect( m, true );
if( !Core.AOS )
{
m.Damage( damage, from );
return damage;
}
Fix( ref phys );
Fix( ref fire );
Fix( ref cold );
Fix( ref pois );
Fix( ref nrgy );
Fix( ref chaos );
Fix( ref direct );
if ( Core.ML && chaos > 0 )
{
switch ( Utility.Random( 5 ) )
{
case 0: phys += chaos; break;
case 1: fire += chaos; break;
case 2: cold += chaos; break;
case 3: pois += chaos; break;
case 4: nrgy += chaos; break;
}
}
BaseQuiver quiver = null;
if ( archer && from != null )
quiver = from.FindItemOnLayer( Layer.Cloak ) as BaseQuiver;
int totalDamage;
if( !ignoreArmor )
{
// Armor Ignore on OSI ignores all defenses, not just physical.
int resPhys = m.PhysicalResistance;
int resFire = m.FireResistance;
int resCold = m.ColdResistance;
int resPois = m.PoisonResistance;
int resNrgy = m.EnergyResistance;
totalDamage = damage * phys * (100 - resPhys);
totalDamage += damage * fire * (100 - resFire);
totalDamage += damage * cold * (100 - resCold);
totalDamage += damage * pois * (100 - resPois);
totalDamage += damage * nrgy * (100 - resNrgy);
totalDamage /= 10000;
if ( Core.ML )
{
totalDamage += damage * direct / 100;
if ( quiver != null )
totalDamage += totalDamage * quiver.DamageIncrease / 100;
}
if( totalDamage < 1 )
totalDamage = 1;
}
else if( Core.ML && m is PlayerMobile && from is PlayerMobile )
{
if ( quiver != null )
damage += damage * quiver.DamageIncrease / 100;
if (!deathStrike)
totalDamage = Math.Min(damage, 35); // Direct Damage cap of 35
else
totalDamage = Math.Min(damage, 70); // Direct Damage cap of 70
}
else
{
totalDamage = damage;
if ( Core.ML && quiver != null )
totalDamage += totalDamage * quiver.DamageIncrease / 100;
}
#region Dragon Barding
if( (from == null || !from.Player) && m.Player && m.Mount is SwampDragon )
{
SwampDragon pet = m.Mount as SwampDragon;
if( pet != null && pet.HasBarding )
{
int percent = (pet.BardingExceptional ? 20 : 10);
int absorbed = Scale( totalDamage, percent );
totalDamage -= absorbed;
pet.BardingHP -= absorbed;
if( pet.BardingHP < 0 )
{
pet.HasBarding = false;
pet.BardingHP = 0;
m.SendLocalizedMessage( 1053031 ); // Your dragon's barding has been destroyed!
}
}
}
#endregion
if( keepAlive && totalDamage > m.Hits )
totalDamage = m.Hits;
if( from != null && !from.Deleted && from.Alive )
{
int reflectPhys = AosAttributes.GetValue( m, AosAttribute.ReflectPhysical );
if( reflectPhys != 0 )
{
if( from is ExodusMinion && ((ExodusMinion)from).FieldActive || from is ExodusOverseer && ((ExodusOverseer)from).FieldActive )
{
from.FixedParticles( 0x376A, 20, 10, 0x2530, EffectLayer.Waist );
from.PlaySound( 0x2F4 );
m.SendAsciiMessage( "Your weapon cannot penetrate the creature's magical barrier" );
}
else
{
from.Damage( Scale( (damage * phys * (100 - (ignoreArmor ? 0 : m.PhysicalResistance))) / 10000, reflectPhys ), m );
}
}
}
m.Damage( totalDamage, from );
return totalDamage;
}
public static void Fix( ref int val )
{
if( val < 0 )
val = 0;
}
public static int Scale( int input, int percent )
{
return (input * percent) / 100;
}
public static int GetStatus(Mobile from, int index)
{
switch (index)
{
// TODO: Account for buffs/debuffs
case 0: return from.GetMaxResistance(ResistanceType.Physical);
case 1: return from.GetMaxResistance(ResistanceType.Fire);
case 2: return from.GetMaxResistance(ResistanceType.Cold);
case 3: return from.GetMaxResistance(ResistanceType.Poison);
case 4: return from.GetMaxResistance(ResistanceType.Energy);
case 5: return AosAttributes.GetValue(from, AosAttribute.DefendChance);
case 6: return 45;
case 7: return AosAttributes.GetValue(from, AosAttribute.AttackChance);
case 8: return AosAttributes.GetValue(from, AosAttribute.WeaponSpeed);
case 9: return AosAttributes.GetValue(from, AosAttribute.WeaponDamage);
case 10: return AosAttributes.GetValue(from, AosAttribute.LowerRegCost);
case 11: return AosAttributes.GetValue(from, AosAttribute.SpellDamage);
case 12: return AosAttributes.GetValue(from, AosAttribute.CastRecovery);
case 13: return AosAttributes.GetValue(from, AosAttribute.CastSpeed);
case 14: return AosAttributes.GetValue(from, AosAttribute.LowerManaCost);
default: return 0;
}
}
}
[Flags]
public enum AosAttribute
{
RegenHits=0x00000001,
RegenStam=0x00000002,
RegenMana=0x00000004,
DefendChance=0x00000008,
AttackChance=0x00000010,
BonusStr=0x00000020,
BonusDex=0x00000040,
BonusInt=0x00000080,
BonusHits=0x00000100,
BonusStam=0x00000200,
BonusMana=0x00000400,
WeaponDamage=0x00000800,
WeaponSpeed=0x00001000,
SpellDamage=0x00002000,
CastRecovery=0x00004000,
CastSpeed=0x00008000,
LowerManaCost=0x00010000,
LowerRegCost=0x00020000,
ReflectPhysical=0x00040000,
EnhancePotions=0x00080000,
Luck=0x00100000,
SpellChanneling=0x00200000,
NightSight = 0x00400000,
IncreasedKarmaLoss = 0x00800000
}
public sealed class AosAttributes : BaseAttributes
{
public AosAttributes( Item owner )
: base( owner )
{
}
public AosAttributes( Item owner, AosAttributes other )
: base( owner, other )
{
}
public AosAttributes( Item owner, GenericReader reader )
: base( owner, reader )
{
}
public static int GetValue( Mobile m, AosAttribute attribute )
{
if( !Core.AOS )
return 0;
List<Item> items = m.Items;
int value = 0;
for( int i = 0; i < items.Count; ++i )
{
Item obj = items[i];
if( obj is BaseWeapon )
{
AosAttributes attrs = ((BaseWeapon)obj).Attributes;
if( attrs != null )
value += attrs[attribute];
if( attribute == AosAttribute.Luck )
value += ((BaseWeapon)obj).GetLuckBonus();
}
else if( obj is BaseArmor )
{
AosAttributes attrs = ((BaseArmor)obj).Attributes;
if( attrs != null )
value += attrs[attribute];
if( attribute == AosAttribute.Luck )
value += ((BaseArmor)obj).GetLuckBonus();
}
else if( obj is BaseJewel )
{
AosAttributes attrs = ((BaseJewel)obj).Attributes;
if( attrs != null )
value += attrs[attribute];
}
else if( obj is BaseClothing )
{
AosAttributes attrs = ((BaseClothing)obj).Attributes;
if( attrs != null )
value += attrs[attribute];
}
else if( obj is Spellbook )
{
AosAttributes attrs = ((Spellbook)obj).Attributes;
if( attrs != null )
value += attrs[attribute];
}
else if( obj is BaseQuiver )
{
AosAttributes attrs = ((BaseQuiver)obj).Attributes;
if( attrs != null )
value += attrs[attribute];
}
else if (obj is BaseTalisman)
{
AosAttributes attrs = ((BaseTalisman)obj).Attributes;
if (attrs != null)
value += attrs[attribute];
}
}
return value;
}
public int this[AosAttribute attribute]
{
get { return GetValue( (int)attribute ); }
set { SetValue( (int)attribute, value ); }
}
public override string ToString()
{
return "...";
}
public void AddStatBonuses( Mobile to )
{
int strBonus = BonusStr;
int dexBonus = BonusDex;
int intBonus = BonusInt;
if ( strBonus != 0 || dexBonus != 0 || intBonus != 0 )
{
string modName = Owner.Serial.ToString();
if ( strBonus != 0 )
to.AddStatMod( new StatMod( StatType.Str, modName + "Str", strBonus, TimeSpan.Zero ) );
if ( dexBonus != 0 )
to.AddStatMod( new StatMod( StatType.Dex, modName + "Dex", dexBonus, TimeSpan.Zero ) );
if ( intBonus != 0 )
to.AddStatMod( new StatMod( StatType.Int, modName + "Int", intBonus, TimeSpan.Zero ) );
}
to.CheckStatTimers();
}
public void RemoveStatBonuses( Mobile from )
{
string modName = Owner.Serial.ToString();
from.RemoveStatMod( modName + "Str" );
from.RemoveStatMod( modName + "Dex" );
from.RemoveStatMod( modName + "Int" );
from.CheckStatTimers();
}
[CommandProperty( AccessLevel.GameMaster )]
public int RegenHits { get { return this[AosAttribute.RegenHits]; } set { this[AosAttribute.RegenHits] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int RegenStam { get { return this[AosAttribute.RegenStam]; } set { this[AosAttribute.RegenStam] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int RegenMana { get { return this[AosAttribute.RegenMana]; } set { this[AosAttribute.RegenMana] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int DefendChance { get { return this[AosAttribute.DefendChance]; } set { this[AosAttribute.DefendChance] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int AttackChance { get { return this[AosAttribute.AttackChance]; } set { this[AosAttribute.AttackChance] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int BonusStr { get { return this[AosAttribute.BonusStr]; } set { this[AosAttribute.BonusStr] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int BonusDex { get { return this[AosAttribute.BonusDex]; } set { this[AosAttribute.BonusDex] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int BonusInt { get { return this[AosAttribute.BonusInt]; } set { this[AosAttribute.BonusInt] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int BonusHits { get { return this[AosAttribute.BonusHits]; } set { this[AosAttribute.BonusHits] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int BonusStam { get { return this[AosAttribute.BonusStam]; } set { this[AosAttribute.BonusStam] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int BonusMana { get { return this[AosAttribute.BonusMana]; } set { this[AosAttribute.BonusMana] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int WeaponDamage { get { return this[AosAttribute.WeaponDamage]; } set { this[AosAttribute.WeaponDamage] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int WeaponSpeed { get { return this[AosAttribute.WeaponSpeed]; } set { this[AosAttribute.WeaponSpeed] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int SpellDamage { get { return this[AosAttribute.SpellDamage]; } set { this[AosAttribute.SpellDamage] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int CastRecovery { get { return this[AosAttribute.CastRecovery]; } set { this[AosAttribute.CastRecovery] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int CastSpeed { get { return this[AosAttribute.CastSpeed]; } set { this[AosAttribute.CastSpeed] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int LowerManaCost { get { return this[AosAttribute.LowerManaCost]; } set { this[AosAttribute.LowerManaCost] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int LowerRegCost { get { return this[AosAttribute.LowerRegCost]; } set { this[AosAttribute.LowerRegCost] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int ReflectPhysical { get { return this[AosAttribute.ReflectPhysical]; } set { this[AosAttribute.ReflectPhysical] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int EnhancePotions { get { return this[AosAttribute.EnhancePotions]; } set { this[AosAttribute.EnhancePotions] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int Luck { get { return this[AosAttribute.Luck]; } set { this[AosAttribute.Luck] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int SpellChanneling { get { return this[AosAttribute.SpellChanneling]; } set { this[AosAttribute.SpellChanneling] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int NightSight { get { return this[AosAttribute.NightSight]; } set { this[AosAttribute.NightSight] = value; } }
[CommandProperty(AccessLevel.GameMaster)]
public int IncreasedKarmaLoss { get { return this[AosAttribute.IncreasedKarmaLoss]; } set { this[AosAttribute.IncreasedKarmaLoss] = value; } }
}
[Flags]
public enum AosWeaponAttribute
{
LowerStatReq=0x00000001,
SelfRepair=0x00000002,
HitLeechHits=0x00000004,
HitLeechStam=0x00000008,
HitLeechMana=0x00000010,
HitLowerAttack=0x00000020,
HitLowerDefend=0x00000040,
HitMagicArrow=0x00000080,
HitHarm=0x00000100,
HitFireball=0x00000200,
HitLightning=0x00000400,
HitDispel=0x00000800,
HitColdArea=0x00001000,
HitFireArea=0x00002000,
HitPoisonArea=0x00004000,
HitEnergyArea=0x00008000,
HitPhysicalArea=0x00010000,
ResistPhysicalBonus=0x00020000,
ResistFireBonus=0x00040000,
ResistColdBonus=0x00080000,
ResistPoisonBonus=0x00100000,
ResistEnergyBonus=0x00200000,
UseBestSkill=0x00400000,
MageWeapon=0x00800000,
DurabilityBonus=0x01000000
}
public sealed class AosWeaponAttributes : BaseAttributes
{
public AosWeaponAttributes( Item owner )
: base( owner )
{
}
public AosWeaponAttributes( Item owner, AosWeaponAttributes other )
: base( owner, other )
{
}
public AosWeaponAttributes( Item owner, GenericReader reader )
: base( owner, reader )
{
}
public static int GetValue( Mobile m, AosWeaponAttribute attribute )
{
if( !Core.AOS )
return 0;
List<Item> items = m.Items;
int value = 0;
for( int i = 0; i < items.Count; ++i )
{
Item obj = items[i];
if( obj is BaseWeapon )
{
AosWeaponAttributes attrs = ((BaseWeapon)obj).WeaponAttributes;
if( attrs != null )
value += attrs[attribute];
}
else if (obj is ElvenGlasses)
{
AosWeaponAttributes attrs = ((ElvenGlasses)obj).WeaponAttributes;
if (attrs != null)
value += attrs[attribute];
}
}
return value;
}
public int this[AosWeaponAttribute attribute]
{
get { return GetValue( (int)attribute ); }
set { SetValue( (int)attribute, value ); }
}
public override string ToString()
{
return "...";
}
[CommandProperty( AccessLevel.GameMaster )]
public int LowerStatReq { get { return this[AosWeaponAttribute.LowerStatReq]; } set { this[AosWeaponAttribute.LowerStatReq] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int SelfRepair { get { return this[AosWeaponAttribute.SelfRepair]; } set { this[AosWeaponAttribute.SelfRepair] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitLeechHits { get { return this[AosWeaponAttribute.HitLeechHits]; } set { this[AosWeaponAttribute.HitLeechHits] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitLeechStam { get { return this[AosWeaponAttribute.HitLeechStam]; } set { this[AosWeaponAttribute.HitLeechStam] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitLeechMana { get { return this[AosWeaponAttribute.HitLeechMana]; } set { this[AosWeaponAttribute.HitLeechMana] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitLowerAttack { get { return this[AosWeaponAttribute.HitLowerAttack]; } set { this[AosWeaponAttribute.HitLowerAttack] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitLowerDefend { get { return this[AosWeaponAttribute.HitLowerDefend]; } set { this[AosWeaponAttribute.HitLowerDefend] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitMagicArrow { get { return this[AosWeaponAttribute.HitMagicArrow]; } set { this[AosWeaponAttribute.HitMagicArrow] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitHarm { get { return this[AosWeaponAttribute.HitHarm]; } set { this[AosWeaponAttribute.HitHarm] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitFireball { get { return this[AosWeaponAttribute.HitFireball]; } set { this[AosWeaponAttribute.HitFireball] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitLightning { get { return this[AosWeaponAttribute.HitLightning]; } set { this[AosWeaponAttribute.HitLightning] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitDispel { get { return this[AosWeaponAttribute.HitDispel]; } set { this[AosWeaponAttribute.HitDispel] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitColdArea { get { return this[AosWeaponAttribute.HitColdArea]; } set { this[AosWeaponAttribute.HitColdArea] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitFireArea { get { return this[AosWeaponAttribute.HitFireArea]; } set { this[AosWeaponAttribute.HitFireArea] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitPoisonArea { get { return this[AosWeaponAttribute.HitPoisonArea]; } set { this[AosWeaponAttribute.HitPoisonArea] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitEnergyArea { get { return this[AosWeaponAttribute.HitEnergyArea]; } set { this[AosWeaponAttribute.HitEnergyArea] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int HitPhysicalArea { get { return this[AosWeaponAttribute.HitPhysicalArea]; } set { this[AosWeaponAttribute.HitPhysicalArea] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int ResistPhysicalBonus { get { return this[AosWeaponAttribute.ResistPhysicalBonus]; } set { this[AosWeaponAttribute.ResistPhysicalBonus] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int ResistFireBonus { get { return this[AosWeaponAttribute.ResistFireBonus]; } set { this[AosWeaponAttribute.ResistFireBonus] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int ResistColdBonus { get { return this[AosWeaponAttribute.ResistColdBonus]; } set { this[AosWeaponAttribute.ResistColdBonus] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int ResistPoisonBonus { get { return this[AosWeaponAttribute.ResistPoisonBonus]; } set { this[AosWeaponAttribute.ResistPoisonBonus] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int ResistEnergyBonus { get { return this[AosWeaponAttribute.ResistEnergyBonus]; } set { this[AosWeaponAttribute.ResistEnergyBonus] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int UseBestSkill { get { return this[AosWeaponAttribute.UseBestSkill]; } set { this[AosWeaponAttribute.UseBestSkill] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int MageWeapon { get { return this[AosWeaponAttribute.MageWeapon]; } set { this[AosWeaponAttribute.MageWeapon] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int DurabilityBonus { get { return this[AosWeaponAttribute.DurabilityBonus]; } set { this[AosWeaponAttribute.DurabilityBonus] = value; } }
}
[Flags]
public enum AosArmorAttribute
{
LowerStatReq=0x00000001,
SelfRepair=0x00000002,
MageArmor=0x00000004,
DurabilityBonus=0x00000008
}
public sealed class AosArmorAttributes : BaseAttributes
{
public AosArmorAttributes( Item owner )
: base( owner )
{
}
public AosArmorAttributes( Item owner, GenericReader reader )
: base( owner, reader )
{
}
public AosArmorAttributes( Item owner, AosArmorAttributes other )
: base( owner, other )
{
}
public static int GetValue( Mobile m, AosArmorAttribute attribute )
{
if( !Core.AOS )
return 0;
List<Item> items = m.Items;
int value = 0;
for( int i = 0; i < items.Count; ++i )
{
Item obj = items[i];
if( obj is BaseArmor )
{
AosArmorAttributes attrs = ((BaseArmor)obj).ArmorAttributes;
if( attrs != null )
value += attrs[attribute];
}
else if( obj is BaseClothing )
{
AosArmorAttributes attrs = ((BaseClothing)obj).ClothingAttributes;
if( attrs != null )
value += attrs[attribute];
}
}
return value;
}
public int this[AosArmorAttribute attribute]
{
get { return GetValue( (int)attribute ); }
set { SetValue( (int)attribute, value ); }
}
public override string ToString()
{
return "...";
}
[CommandProperty( AccessLevel.GameMaster )]
public int LowerStatReq { get { return this[AosArmorAttribute.LowerStatReq]; } set { this[AosArmorAttribute.LowerStatReq] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int SelfRepair { get { return this[AosArmorAttribute.SelfRepair]; } set { this[AosArmorAttribute.SelfRepair] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int MageArmor { get { return this[AosArmorAttribute.MageArmor]; } set { this[AosArmorAttribute.MageArmor] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int DurabilityBonus { get { return this[AosArmorAttribute.DurabilityBonus]; } set { this[AosArmorAttribute.DurabilityBonus] = value; } }
}
public sealed class AosSkillBonuses : BaseAttributes
{
private List<SkillMod> m_Mods;
public AosSkillBonuses( Item owner )
: base( owner )
{
}
public AosSkillBonuses( Item owner, GenericReader reader )
: base( owner, reader )
{
}
public AosSkillBonuses( Item owner, AosSkillBonuses other )
: base( owner, other )
{
}
public void GetProperties( ObjectPropertyList list )
{
for( int i = 0; i < 5; ++i )
{
SkillName skill;
double bonus;
if( !GetValues( i, out skill, out bonus ) )
continue;
list.Add(1060451 + i, "#{0}\t{1}", GetLabel(skill), bonus);
}
}
public static int GetLabel(SkillName skill)
{
switch (skill)
{
case SkillName.EvalInt: return 1002070; // Evaluate Intelligence
case SkillName.Forensics: return 1002078; // Forensic Evaluation
case SkillName.Lockpicking: return 1002097; // Lockpicking
default: return 1044060 + (int)skill;
}
}
public void AddTo( Mobile m )
{
Remove();
for( int i = 0; i < 5; ++i )
{
SkillName skill;
double bonus;
if( !GetValues( i, out skill, out bonus ) )
continue;
if( m_Mods == null )
m_Mods = new List<SkillMod>();
SkillMod sk = new DefaultSkillMod( skill, true, bonus );
sk.ObeyCap = true;
m.AddSkillMod( sk );
m_Mods.Add( sk );
}
}
public void Remove()
{
if( m_Mods == null )
return;
for( int i = 0; i < m_Mods.Count; ++i ) {
Mobile m = m_Mods[i].Owner;
m_Mods[i].Remove();
if ( Core.ML )
CheckCancelMorph ( m );
}
m_Mods = null;
}
public bool GetValues( int index, out SkillName skill, out double bonus )
{
int v = GetValue( 1 << index );
int vSkill = 0;
int vBonus = 0;
for( int i = 0; i < 16; ++i )
{
vSkill <<= 1;
vSkill |= (v & 1);
v >>= 1;
vBonus <<= 1;
vBonus |= (v & 1);
v >>= 1;
}
skill = (SkillName)vSkill;
bonus = (double)vBonus / 10;
return (bonus != 0);
}
public void SetValues( int index, SkillName skill, double bonus )
{
int v = 0;
int vSkill = (int)skill;
int vBonus = (int)(bonus * 10);
for( int i = 0; i < 16; ++i )
{
v <<= 1;
v |= (vBonus & 1);
vBonus >>= 1;
v <<= 1;
v |= (vSkill & 1);
vSkill >>= 1;
}
SetValue( 1 << index, v );
}
public SkillName GetSkill( int index )
{
SkillName skill;
double bonus;
GetValues( index, out skill, out bonus );
return skill;
}
public void SetSkill( int index, SkillName skill )
{
SetValues( index, skill, GetBonus( index ) );
}
public double GetBonus( int index )
{
SkillName skill;
double bonus;
GetValues( index, out skill, out bonus );
return bonus;
}
public void SetBonus( int index, double bonus )
{
SetValues( index, GetSkill( index ), bonus );
}
public override string ToString()
{
return "...";
}
public void CheckCancelMorph ( Mobile m )
{
if ( m == null )
return;
double minSkill, maxSkill;
AnimalFormContext acontext = AnimalForm.GetContext( m );
TransformContext context = TransformationSpellHelper.GetContext( m );
if ( context != null ) {
Spell spell = context.Spell as Spell;
spell.GetCastSkills ( out minSkill, out maxSkill );
if ( m.Skills[spell.CastSkill].Value < minSkill )
TransformationSpellHelper.RemoveContext( m, context, true );
}
if ( acontext != null ) {
int i;
for ( i = 0; i < AnimalForm.Entries.Length; ++i )
if ( AnimalForm.Entries[i].Type == acontext.Type )
break;
if ( m.Skills[SkillName.Ninjitsu].Value < AnimalForm.Entries[i].ReqSkill )
AnimalForm.RemoveContext( m, true );
}
if ( !m.CanBeginAction ( typeof ( PolymorphSpell ) ) && m.Skills[SkillName.Magery].Value < 66.1 ) {
m.BodyMod = 0;
m.HueMod = -1;
m.NameMod = null;
m.EndAction( typeof( PolymorphSpell ) );
BaseArmor.ValidateMobile( m );
BaseClothing.ValidateMobile( m );
}
if ( !m.CanBeginAction ( typeof ( IncognitoSpell ) ) && m.Skills[SkillName.Magery].Value < 38.1 ) {
if ( m is PlayerMobile )
((PlayerMobile)m).SetHairMods( -1, -1 );
m.BodyMod = 0;
m.HueMod = -1;
m.NameMod = null;
m.EndAction( typeof( IncognitoSpell ) );
BaseArmor.ValidateMobile( m );
BaseClothing.ValidateMobile( m );
BuffInfo.RemoveBuff( m, BuffIcon.Incognito );
}
return;
}
[CommandProperty( AccessLevel.GameMaster )]
public double Skill_1_Value { get { return GetBonus( 0 ); } set { SetBonus( 0, value ); } }
[CommandProperty( AccessLevel.GameMaster )]
public SkillName Skill_1_Name { get { return GetSkill( 0 ); } set { SetSkill( 0, value ); } }
[CommandProperty( AccessLevel.GameMaster )]
public double Skill_2_Value { get { return GetBonus( 1 ); } set { SetBonus( 1, value ); } }
[CommandProperty( AccessLevel.GameMaster )]
public SkillName Skill_2_Name { get { return GetSkill( 1 ); } set { SetSkill( 1, value ); } }
[CommandProperty( AccessLevel.GameMaster )]
public double Skill_3_Value { get { return GetBonus( 2 ); } set { SetBonus( 2, value ); } }
[CommandProperty( AccessLevel.GameMaster )]
public SkillName Skill_3_Name { get { return GetSkill( 2 ); } set { SetSkill( 2, value ); } }
[CommandProperty( AccessLevel.GameMaster )]
public double Skill_4_Value { get { return GetBonus( 3 ); } set { SetBonus( 3, value ); } }
[CommandProperty( AccessLevel.GameMaster )]
public SkillName Skill_4_Name { get { return GetSkill( 3 ); } set { SetSkill( 3, value ); } }
[CommandProperty( AccessLevel.GameMaster )]
public double Skill_5_Value { get { return GetBonus( 4 ); } set { SetBonus( 4, value ); } }
[CommandProperty( AccessLevel.GameMaster )]
public SkillName Skill_5_Name { get { return GetSkill( 4 ); } set { SetSkill( 4, value ); } }
}
[Flags]
public enum AosElementAttribute
{
Physical=0x00000001,
Fire=0x00000002,
Cold=0x00000004,
Poison=0x00000008,
Energy=0x00000010,
Chaos=0x00000020,
Direct=0x00000040
}
public sealed class AosElementAttributes : BaseAttributes
{
public AosElementAttributes( Item owner )
: base( owner )
{
}
public AosElementAttributes( Item owner, AosElementAttributes other )
: base( owner, other )
{
}
public AosElementAttributes( Item owner, GenericReader reader )
: base( owner, reader )
{
}
public int this[AosElementAttribute attribute]
{
get { return GetValue( (int)attribute ); }
set { SetValue( (int)attribute, value ); }
}
public override string ToString()
{
return "...";
}
[CommandProperty( AccessLevel.GameMaster )]
public int Physical { get { return this[AosElementAttribute.Physical]; } set { this[AosElementAttribute.Physical] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int Fire { get { return this[AosElementAttribute.Fire]; } set { this[AosElementAttribute.Fire] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int Cold { get { return this[AosElementAttribute.Cold]; } set { this[AosElementAttribute.Cold] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int Poison { get { return this[AosElementAttribute.Poison]; } set { this[AosElementAttribute.Poison] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int Energy { get { return this[AosElementAttribute.Energy]; } set { this[AosElementAttribute.Energy] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int Chaos { get { return this[AosElementAttribute.Chaos]; } set { this[AosElementAttribute.Chaos] = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int Direct { get { return this[AosElementAttribute.Direct]; } set { this[AosElementAttribute.Direct] = value; } }
}
[PropertyObject]
public abstract class BaseAttributes
{
private Item m_Owner;
private uint m_Names;
private int[] m_Values;
private static int[] m_Empty = new int[0];
public bool IsEmpty { get { return (m_Names == 0); } }
public Item Owner { get { return m_Owner; } }
public BaseAttributes( Item owner )
{
m_Owner = owner;
m_Values = m_Empty;
}
public BaseAttributes( Item owner, BaseAttributes other )
{
m_Owner = owner;
m_Values = new int[other.m_Values.Length];
other.m_Values.CopyTo( m_Values, 0 );
m_Names = other.m_Names;
}
public BaseAttributes( Item owner, GenericReader reader )
{
m_Owner = owner;
int version = reader.ReadByte();
switch( version )
{
case 1:
{
m_Names = reader.ReadUInt();
m_Values = new int[reader.ReadEncodedInt()];
for( int i = 0; i < m_Values.Length; ++i )
m_Values[i] = reader.ReadEncodedInt();
break;
}
case 0:
{
m_Names = reader.ReadUInt();
m_Values = new int[reader.ReadInt()];
for( int i = 0; i < m_Values.Length; ++i )
m_Values[i] = reader.ReadInt();
break;
}
}
}
public void Serialize( GenericWriter writer )
{
writer.Write( (byte)1 ); // version;
writer.Write( (uint)m_Names );
writer.WriteEncodedInt( (int)m_Values.Length );
for( int i = 0; i < m_Values.Length; ++i )
writer.WriteEncodedInt( (int)m_Values[i] );
}
public int GetValue( int bitmask )
{
if( !Core.AOS )
return 0;
uint mask = (uint)bitmask;
if( (m_Names & mask) == 0 )
return 0;
int index = GetIndex( mask );
if( index >= 0 && index < m_Values.Length )
return m_Values[index];
return 0;
}
public void SetValue( int bitmask, int value )
{
if( (bitmask == (int)AosWeaponAttribute.DurabilityBonus) && (this is AosWeaponAttributes) )
{
if( m_Owner is BaseWeapon )
((BaseWeapon)m_Owner).UnscaleDurability();
}
else if( (bitmask == (int)AosArmorAttribute.DurabilityBonus) && (this is AosArmorAttributes) )
{
if( m_Owner is BaseArmor )
((BaseArmor)m_Owner).UnscaleDurability();
else if( m_Owner is BaseClothing )
((BaseClothing)m_Owner).UnscaleDurability();
}
uint mask = (uint)bitmask;
if( value != 0 )
{
if( (m_Names & mask) != 0 )
{
int index = GetIndex( mask );
if( index >= 0 && index < m_Values.Length )
m_Values[index] = value;
}
else
{
int index = GetIndex( mask );
if( index >= 0 && index <= m_Values.Length )
{
int[] old = m_Values;
m_Values = new int[old.Length + 1];
for( int i = 0; i < index; ++i )
m_Values[i] = old[i];
m_Values[index] = value;
for( int i = index; i < old.Length; ++i )
m_Values[i + 1] = old[i];
m_Names |= mask;
}
}
}
else if( (m_Names & mask) != 0 )
{
int index = GetIndex( mask );
if( index >= 0 && index < m_Values.Length )
{
m_Names &= ~mask;
if( m_Values.Length == 1 )
{
m_Values = m_Empty;
}
else
{
int[] old = m_Values;
m_Values = new int[old.Length - 1];
for( int i = 0; i < index; ++i )
m_Values[i] = old[i];
for( int i = index + 1; i < old.Length; ++i )
m_Values[i - 1] = old[i];
}
}
}
if( (bitmask == (int)AosWeaponAttribute.DurabilityBonus) && (this is AosWeaponAttributes) )
{
if( m_Owner is BaseWeapon )
((BaseWeapon)m_Owner).ScaleDurability();
}
else if( (bitmask == (int)AosArmorAttribute.DurabilityBonus) && (this is AosArmorAttributes) )
{
if( m_Owner is BaseArmor )
((BaseArmor)m_Owner).ScaleDurability();
else if( m_Owner is BaseClothing )
((BaseClothing)m_Owner).ScaleDurability();
}
if( m_Owner.Parent is Mobile )
{
Mobile m = (Mobile)m_Owner.Parent;
m.CheckStatTimers();
m.UpdateResistances();
m.Delta( MobileDelta.Stat | MobileDelta.WeaponDamage | MobileDelta.Hits | MobileDelta.Stam | MobileDelta.Mana );
if( this is AosSkillBonuses )
{
((AosSkillBonuses)this).Remove();
((AosSkillBonuses)this).AddTo( m );
}
}
m_Owner.InvalidateProperties();
}
private int GetIndex( uint mask )
{
int index = 0;
uint ourNames = m_Names;
uint currentBit = 1;
while( currentBit != mask )
{
if( (ourNames & currentBit) != 0 )
++index;
if( currentBit == 0x80000000 )
return -1;
currentBit <<= 1;
}
return index;
}
}
}
| |
#region usings
using System;
using System.ComponentModel.Composition;
using System.Collections;
using System.Collections.Generic;
using VVVV.PluginInterfaces.V1;
using VVVV.PluginInterfaces.V2;
using VVVV.Utils.VColor;
using VVVV.Utils.VMath;
using Emotiv;
using VVVV.Core.Logging;
#endregion usings
namespace VVVV.EmotivEpoc
{
#region PluginInfo
[PluginInfo(Name = "EmotivEpoc",
Category = "Device",
Help = "Get information from Emotiv Epoc device",
Tags = "Emotiv, Epoc, EEG",
AutoEvaluate = true)]
#endregion PluginInfo
public class DeviceEmotivEpocNode : IPluginEvaluate, IDisposable, IPartImportsSatisfiedNotification
{
#region enums
public enum TEmotivConnectionMode {
EmoEngine,
EmotivControlPanel,
EmoComposer
}
#endregion enums
#region fields & pins
[Input("Connect", DefaultBoolean = false, IsToggle = true, IsSingle = true)]
public IDiffSpread<bool> FConnect;
[Input("Server", DefaultString = "127.0.0.1", IsSingle = true)]
public IDiffSpread<string> FServer;
[Input("Connection Mode", IsSingle = true, DefaultEnumEntry = "EmoEngine")]
public IDiffSpread<TEmotivConnectionMode> ConnectionMode;
[Output("EmoState", IsSingle = true)]
public ISpread<EmoState> FEmoState;
[Output("Headset On", IsToggle = true)]
public ISpread<bool> FHeadsetOn;
[Output("Contact Quality")]
public ISpread<EdkDll.EE_EEG_ContactQuality_t> FCQ;
[Output("Signal Strength")]
public ISpread<EdkDll.EE_SignalStrength_t> FSignalStrength;
[Output("Battery Level")]
public ISpread<Int32> FBatteryCharge;
[Output("Battery Max Level")]
public ISpread<Int32> FBatteryMaxCharge;
[Output("Time From Start")]
public ISpread<Single> FTimeFromStart;
[Output("Connected", IsToggle = true, IsSingle = true)]
public ISpread<bool> FConnected;
[Import()]
public ILogger FLogger;
#endregion fields & pins
//Member variables
private EmoEngine mEngine;
private EmoState mEmoState;
private bool mIsHeadsetOn = false;
private EdkDll.EE_EEG_ContactQuality_t[] mCQ = new EdkDll.EE_EEG_ContactQuality_t[] { EdkDll.EE_EEG_ContactQuality_t.EEG_CQ_NO_SIGNAL };
private EdkDll.EE_SignalStrength_t mSignalStrength;
private Int32 mBatteryCharge = 0;
private Int32 mBatteryMaxCharge = 0;
private Single mTimeFromStart = 0;
private bool mIsConnected = false;
private static object syncLock = new Object();
//Contructor
public DeviceEmotivEpocNode() {
try
{
mEngine = EmoEngine.Instance;
//Register event handler
mEngine.EmoEngineConnected += new EmoEngine.EmoEngineConnectedEventHandler(EmoEngineConnectedCB);
mEngine.EmoEngineDisconnected += new EmoEngine.EmoEngineDisconnectedEventHandler(EmoEngineDisconnectedCB);
mEngine.EmoEngineEmoStateUpdated += new EmoEngine.EmoEngineEmoStateUpdatedEventHandler(EmoEngineEmoStateUpdatedCB);
}
catch(EmoEngineException e)
{
FLogger.Log(LogType.Debug, e.ToString());
}
}
//I/O pin that needs to be setup only once after constructor
public void OnImportsSatisfied() {
}
//Destructor
public void Dispose() {
mEngine.Disconnect();
}
//Create the connection
protected void Connect(TEmotivConnectionMode iMode, string iServer) {
switch(iMode) {
case TEmotivConnectionMode.EmoEngine:
mEngine.Connect();
break;
case TEmotivConnectionMode.EmotivControlPanel:
mEngine.RemoteConnect(iServer, 3008);
break;
case TEmotivConnectionMode.EmoComposer:
mEngine.RemoteConnect(iServer, 1726);
break;
}
}
//Handling internal connection status
protected void EmoEngineConnectedCB(object sender, EmoEngineEventArgs e)
{
mIsConnected = true;
}
protected void EmoEngineDisconnectedCB(object sender, EmoEngineEventArgs e)
{
mIsConnected = false;
//Reset device status
lock(syncLock)
{
mIsHeadsetOn = false;
mCQ = new EdkDll.EE_EEG_ContactQuality_t[] {EdkDll.EE_EEG_ContactQuality_t.EEG_CQ_NO_SIGNAL};
mSignalStrength = EdkDll.EE_SignalStrength_t.NO_SIGNAL;
mBatteryCharge = 0;
mBatteryMaxCharge = 0;
mTimeFromStart = 0;
}
}
protected void EmoEngineEmoStateUpdatedCB(object sender, EmoStateUpdatedEventArgs e)
{
EmoState es = e.emoState;
//Update connexion status
lock(syncLock)
{
mEmoState = es;
mIsHeadsetOn = es.GetHeadsetOn() != 0;
mCQ = es.GetContactQualityFromAllChannels();
mSignalStrength = es.GetWirelessSignalStatus();
es.GetBatteryChargeLevel(out mBatteryCharge, out mBatteryMaxCharge);
mTimeFromStart = es.GetTimeFromStart();
}
}
//called when data for any output pin is requested
public void Evaluate(int SpreadMax)
{
if(FConnect.IsChanged)
{
if(FConnect[0] && !mIsConnected)
Connect(ConnectionMode[0], FServer[0]);
else if(!FConnect[0] && mIsConnected)
mEngine.Disconnect();
}
if((FServer.IsChanged || ConnectionMode.IsChanged) && mIsConnected)
{
mEngine.Disconnect();
Connect(ConnectionMode[0], FServer[0]);
}
if(mIsConnected)
{
//Process events
mEngine.ProcessEvents(1000);
}
//Fill the output pins
if (mIsConnected)
{
lock (syncLock)
{
if (mEmoState != null)
{
FEmoState.SliceCount = 1;
FEmoState[0] = mEmoState;
}
else
FEmoState.SliceCount = 0;
FHeadsetOn.SliceCount = 1;
FHeadsetOn[0] = mIsHeadsetOn;
FCQ.SliceCount = mCQ.Length;
for (int i = 0; i < mCQ.Length; ++i)
FCQ[i] = mCQ[i];
FSignalStrength.SliceCount = 1;
FSignalStrength[0] = mSignalStrength;
FBatteryCharge.SliceCount = 1;
FBatteryCharge[0] = mBatteryCharge;
FBatteryMaxCharge.SliceCount = 1;
FBatteryMaxCharge[0] = mBatteryMaxCharge;
FTimeFromStart.SliceCount = 1;
FTimeFromStart[0] = mTimeFromStart;
}
}
FConnected.SliceCount = 1;
FConnected[0] = mIsConnected;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.XPath;
namespace MS.Internal.Xml.XPath
{
internal class XPathParser
{
XPathScanner scanner;
private XPathParser(XPathScanner scanner)
{
this.scanner = scanner;
}
public static AstNode ParseXPathExpresion(string xpathExpresion)
{
XPathScanner scanner = new XPathScanner(xpathExpresion);
XPathParser parser = new XPathParser(scanner);
AstNode result = parser.ParseExpresion(null);
if (scanner.Kind != XPathScanner.LexKind.Eof)
{
throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText);
}
return result;
}
public static AstNode ParseXPathPattern(string xpathPattern)
{
XPathScanner scanner = new XPathScanner(xpathPattern);
XPathParser parser = new XPathParser(scanner);
AstNode result = parser.ParsePattern();
if (scanner.Kind != XPathScanner.LexKind.Eof)
{
throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText);
}
return result;
}
// --------------- Expresion Parsing ----------------------
//The recursive is like
//ParseOrExpr->ParseAndExpr->ParseEqualityExpr->ParseRelationalExpr...->ParseFilterExpr->ParsePredicate->ParseExpresion
//So put 200 limitation here will max cause about 2000~3000 depth stack.
private int parseDepth = 0;
private const int MaxParseDepth = 200;
private AstNode ParseExpresion(AstNode qyInput)
{
if (++parseDepth > MaxParseDepth)
{
throw XPathException.Create(SR.Xp_QueryTooComplex);
}
AstNode result = ParseOrExpr(qyInput);
--parseDepth;
return result;
}
//>> OrExpr ::= ( OrExpr 'or' )? AndExpr
private AstNode ParseOrExpr(AstNode qyInput)
{
AstNode opnd = ParseAndExpr(qyInput);
do
{
if (!TestOp("or"))
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.OR, opnd, ParseAndExpr(qyInput));
} while (true);
}
//>> AndExpr ::= ( AndExpr 'and' )? EqualityExpr
private AstNode ParseAndExpr(AstNode qyInput)
{
AstNode opnd = ParseEqualityExpr(qyInput);
do
{
if (!TestOp("and"))
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.AND, opnd, ParseEqualityExpr(qyInput));
} while (true);
}
//>> EqualityOp ::= '=' | '!='
//>> EqualityExpr ::= ( EqualityExpr EqualityOp )? RelationalExpr
private AstNode ParseEqualityExpr(AstNode qyInput)
{
AstNode opnd = ParseRelationalExpr(qyInput);
do
{
Operator.Op op = (
this.scanner.Kind == XPathScanner.LexKind.Eq ? Operator.Op.EQ :
this.scanner.Kind == XPathScanner.LexKind.Ne ? Operator.Op.NE :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseRelationalExpr(qyInput));
} while (true);
}
//>> RelationalOp ::= '<' | '>' | '<=' | '>='
//>> RelationalExpr ::= ( RelationalExpr RelationalOp )? AdditiveExpr
private AstNode ParseRelationalExpr(AstNode qyInput)
{
AstNode opnd = ParseAdditiveExpr(qyInput);
do
{
Operator.Op op = (
this.scanner.Kind == XPathScanner.LexKind.Lt ? Operator.Op.LT :
this.scanner.Kind == XPathScanner.LexKind.Le ? Operator.Op.LE :
this.scanner.Kind == XPathScanner.LexKind.Gt ? Operator.Op.GT :
this.scanner.Kind == XPathScanner.LexKind.Ge ? Operator.Op.GE :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseAdditiveExpr(qyInput));
} while (true);
}
//>> AdditiveOp ::= '+' | '-'
//>> AdditiveExpr ::= ( AdditiveExpr AdditiveOp )? MultiplicativeExpr
private AstNode ParseAdditiveExpr(AstNode qyInput)
{
AstNode opnd = ParseMultiplicativeExpr(qyInput);
do
{
Operator.Op op = (
this.scanner.Kind == XPathScanner.LexKind.Plus ? Operator.Op.PLUS :
this.scanner.Kind == XPathScanner.LexKind.Minus ? Operator.Op.MINUS :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseMultiplicativeExpr(qyInput));
} while (true);
}
//>> MultiplicativeOp ::= '*' | 'div' | 'mod'
//>> MultiplicativeExpr ::= ( MultiplicativeExpr MultiplicativeOp )? UnaryExpr
private AstNode ParseMultiplicativeExpr(AstNode qyInput)
{
AstNode opnd = ParseUnaryExpr(qyInput);
do
{
Operator.Op op = (
this.scanner.Kind == XPathScanner.LexKind.Star ? Operator.Op.MUL :
TestOp("div") ? Operator.Op.DIV :
TestOp("mod") ? Operator.Op.MOD :
/*default :*/ Operator.Op.INVALID
);
if (op == Operator.Op.INVALID)
{
return opnd;
}
NextLex();
opnd = new Operator(op, opnd, ParseUnaryExpr(qyInput));
} while (true);
}
//>> UnaryExpr ::= UnionExpr | '-' UnaryExpr
private AstNode ParseUnaryExpr(AstNode qyInput)
{
bool minus = false;
while (this.scanner.Kind == XPathScanner.LexKind.Minus)
{
NextLex();
minus = !minus;
}
if (minus)
{
return new Operator(Operator.Op.MUL, ParseUnionExpr(qyInput), new Operand(-1));
}
else
{
return ParseUnionExpr(qyInput);
}
}
//>> UnionExpr ::= ( UnionExpr '|' )? PathExpr
private AstNode ParseUnionExpr(AstNode qyInput)
{
AstNode opnd = ParsePathExpr(qyInput);
do
{
if (this.scanner.Kind != XPathScanner.LexKind.Union)
{
return opnd;
}
NextLex();
AstNode opnd2 = ParsePathExpr(qyInput);
CheckNodeSet(opnd.ReturnType);
CheckNodeSet(opnd2.ReturnType);
opnd = new Operator(Operator.Op.UNION, opnd, opnd2);
} while (true);
}
private static bool IsNodeType(XPathScanner scaner)
{
return (
scaner.Prefix.Length == 0 && (
scaner.Name == "node" ||
scaner.Name == "text" ||
scaner.Name == "processing-instruction" ||
scaner.Name == "comment"
)
);
}
//>> PathOp ::= '/' | '//'
//>> PathExpr ::= LocationPath |
//>> FilterExpr ( PathOp RelativeLocationPath )?
private AstNode ParsePathExpr(AstNode qyInput)
{
AstNode opnd;
if (IsPrimaryExpr(this.scanner))
{ // in this moment we shoud distinct LocationPas vs FilterExpr (which starts from is PrimaryExpr)
opnd = ParseFilterExpr(qyInput);
if (this.scanner.Kind == XPathScanner.LexKind.Slash)
{
NextLex();
opnd = ParseRelativeLocationPath(opnd);
}
else if (this.scanner.Kind == XPathScanner.LexKind.SlashSlash)
{
NextLex();
opnd = ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, opnd));
}
}
else
{
opnd = ParseLocationPath(null);
}
return opnd;
}
//>> FilterExpr ::= PrimaryExpr | FilterExpr Predicate
private AstNode ParseFilterExpr(AstNode qyInput)
{
AstNode opnd = ParsePrimaryExpr(qyInput);
while (this.scanner.Kind == XPathScanner.LexKind.LBracket)
{
// opnd must be a query
opnd = new Filter(opnd, ParsePredicate(opnd));
}
return opnd;
}
//>> Predicate ::= '[' Expr ']'
private AstNode ParsePredicate(AstNode qyInput)
{
AstNode opnd;
// we have predicates. Check that input type is NodeSet
CheckNodeSet(qyInput.ReturnType);
PassToken(XPathScanner.LexKind.LBracket);
opnd = ParseExpresion(qyInput);
PassToken(XPathScanner.LexKind.RBracket);
return opnd;
}
//>> LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
private AstNode ParseLocationPath(AstNode qyInput)
{
if (this.scanner.Kind == XPathScanner.LexKind.Slash)
{
NextLex();
AstNode opnd = new Root();
if (IsStep(this.scanner.Kind))
{
opnd = ParseRelativeLocationPath(opnd);
}
return opnd;
}
else if (this.scanner.Kind == XPathScanner.LexKind.SlashSlash)
{
NextLex();
return ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, new Root()));
}
else
{
return ParseRelativeLocationPath(qyInput);
}
} // ParseLocationPath
//>> PathOp ::= '/' | '//'
//>> RelativeLocationPath ::= ( RelativeLocationPath PathOp )? Step
private AstNode ParseRelativeLocationPath(AstNode qyInput)
{
AstNode opnd = qyInput;
do
{
opnd = ParseStep(opnd);
if (XPathScanner.LexKind.SlashSlash == this.scanner.Kind)
{
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd);
}
else if (XPathScanner.LexKind.Slash == this.scanner.Kind)
{
NextLex();
}
else
{
break;
}
}
while (true);
return opnd;
}
private static bool IsStep(XPathScanner.LexKind lexKind)
{
return (
lexKind == XPathScanner.LexKind.Dot ||
lexKind == XPathScanner.LexKind.DotDot ||
lexKind == XPathScanner.LexKind.At ||
lexKind == XPathScanner.LexKind.Axe ||
lexKind == XPathScanner.LexKind.Star ||
lexKind == XPathScanner.LexKind.Name // NodeTest is also Name
);
}
//>> Step ::= '.' | '..' | ( AxisName '::' | '@' )? NodeTest Predicate*
private AstNode ParseStep(AstNode qyInput)
{
AstNode opnd;
if (XPathScanner.LexKind.Dot == this.scanner.Kind)
{ //>> '.'
NextLex();
opnd = new Axis(Axis.AxisType.Self, qyInput);
}
else if (XPathScanner.LexKind.DotDot == this.scanner.Kind)
{ //>> '..'
NextLex();
opnd = new Axis(Axis.AxisType.Parent, qyInput);
}
else
{ //>> ( AxisName '::' | '@' )? NodeTest Predicate*
Axis.AxisType axisType = Axis.AxisType.Child;
switch (this.scanner.Kind)
{
case XPathScanner.LexKind.At: //>> '@'
axisType = Axis.AxisType.Attribute;
NextLex();
break;
case XPathScanner.LexKind.Axe: //>> AxisName '::'
axisType = GetAxis();
NextLex();
break;
}
XPathNodeType nodeType = (
axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute :
// axisType == Axis.AxisType.Namespace ? XPathNodeType.Namespace : // No Idea why it's this way but othervise Axes doesn't work
/* default: */ XPathNodeType.Element
);
opnd = ParseNodeTest(qyInput, axisType, nodeType);
while (XPathScanner.LexKind.LBracket == this.scanner.Kind)
{
opnd = new Filter(opnd, ParsePredicate(opnd));
}
}
return opnd;
}
//>> NodeTest ::= NameTest | 'comment ()' | 'text ()' | 'node ()' | 'processing-instruction (' Literal ? ')'
private AstNode ParseNodeTest(AstNode qyInput, Axis.AxisType axisType, XPathNodeType nodeType)
{
string nodeName, nodePrefix;
switch (this.scanner.Kind)
{
case XPathScanner.LexKind.Name:
if (this.scanner.CanBeFunction && IsNodeType(this.scanner))
{
nodePrefix = string.Empty;
nodeName = string.Empty;
nodeType = (
this.scanner.Name == "comment" ? XPathNodeType.Comment :
this.scanner.Name == "text" ? XPathNodeType.Text :
this.scanner.Name == "node" ? XPathNodeType.All :
this.scanner.Name == "processing-instruction" ? XPathNodeType.ProcessingInstruction :
/* default: */ XPathNodeType.Root
);
Debug.Assert(nodeType != XPathNodeType.Root);
NextLex();
PassToken(XPathScanner.LexKind.LParens);
if (nodeType == XPathNodeType.ProcessingInstruction)
{
if (this.scanner.Kind != XPathScanner.LexKind.RParens)
{ //>> 'processing-instruction (' Literal ')'
CheckToken(XPathScanner.LexKind.String);
nodeName = this.scanner.StringValue;
NextLex();
}
}
PassToken(XPathScanner.LexKind.RParens);
}
else
{
nodePrefix = this.scanner.Prefix;
nodeName = this.scanner.Name;
NextLex();
if (nodeName == "*")
{
nodeName = string.Empty;
}
}
break;
case XPathScanner.LexKind.Star:
nodePrefix = string.Empty;
nodeName = string.Empty;
NextLex();
break;
default:
throw XPathException.Create(SR.Xp_NodeSetExpected, this.scanner.SourceText);
}
return new Axis(axisType, qyInput, nodePrefix, nodeName, nodeType);
}
private static bool IsPrimaryExpr(XPathScanner scanner)
{
return (
scanner.Kind == XPathScanner.LexKind.String ||
scanner.Kind == XPathScanner.LexKind.Number ||
scanner.Kind == XPathScanner.LexKind.Dollar ||
scanner.Kind == XPathScanner.LexKind.LParens ||
scanner.Kind == XPathScanner.LexKind.Name && scanner.CanBeFunction && !IsNodeType(scanner)
);
}
//>> PrimaryExpr ::= Literal | Number | VariableReference | '(' Expr ')' | FunctionCall
private AstNode ParsePrimaryExpr(AstNode qyInput)
{
Debug.Assert(IsPrimaryExpr(this.scanner));
AstNode opnd = null;
switch (this.scanner.Kind)
{
case XPathScanner.LexKind.String:
opnd = new Operand(this.scanner.StringValue);
NextLex();
break;
case XPathScanner.LexKind.Number:
opnd = new Operand(this.scanner.NumberValue);
NextLex();
break;
case XPathScanner.LexKind.Dollar:
NextLex();
CheckToken(XPathScanner.LexKind.Name);
opnd = new Variable(this.scanner.Name, this.scanner.Prefix);
NextLex();
break;
case XPathScanner.LexKind.LParens:
NextLex();
opnd = ParseExpresion(qyInput);
if (opnd.Type != AstNode.AstType.ConstantOperand)
{
opnd = new Group(opnd);
}
PassToken(XPathScanner.LexKind.RParens);
break;
case XPathScanner.LexKind.Name:
if (this.scanner.CanBeFunction && !IsNodeType(this.scanner))
{
opnd = ParseMethod(null);
}
break;
}
Debug.Assert(opnd != null, "IsPrimaryExpr() was true. We should recognize this lex.");
return opnd;
}
private AstNode ParseMethod(AstNode qyInput)
{
List<AstNode> argList = new List<AstNode>();
string name = this.scanner.Name;
string prefix = this.scanner.Prefix;
PassToken(XPathScanner.LexKind.Name);
PassToken(XPathScanner.LexKind.LParens);
if (this.scanner.Kind != XPathScanner.LexKind.RParens)
{
do
{
argList.Add(ParseExpresion(qyInput));
if (this.scanner.Kind == XPathScanner.LexKind.RParens)
{
break;
}
PassToken(XPathScanner.LexKind.Comma);
} while (true);
}
PassToken(XPathScanner.LexKind.RParens);
if (prefix.Length == 0)
{
ParamInfo pi;
if (functionTable.TryGetValue(name, out pi))
{
int argCount = argList.Count;
if (argCount < pi.Minargs)
{
throw XPathException.Create(SR.Xp_InvalidNumArgs, name, this.scanner.SourceText);
}
if (pi.FType == Function.FunctionType.FuncConcat)
{
for (int i = 0; i < argCount; i++)
{
AstNode arg = (AstNode)argList[i];
if (arg.ReturnType != XPathResultType.String)
{
arg = new Function(Function.FunctionType.FuncString, arg);
}
argList[i] = arg;
}
}
else
{
if (pi.Maxargs < argCount)
{
throw XPathException.Create(SR.Xp_InvalidNumArgs, name, this.scanner.SourceText);
}
if (pi.ArgTypes.Length < argCount)
{
argCount = pi.ArgTypes.Length; // argument we have the type specified (can be < pi.Minargs)
}
for (int i = 0; i < argCount; i++)
{
AstNode arg = (AstNode)argList[i];
if (
pi.ArgTypes[i] != XPathResultType.Any &&
pi.ArgTypes[i] != arg.ReturnType
)
{
switch (pi.ArgTypes[i])
{
case XPathResultType.NodeSet:
if (!(arg is Variable) && !(arg is Function && arg.ReturnType == XPathResultType.Any))
{
throw XPathException.Create(SR.Xp_InvalidArgumentType, name, this.scanner.SourceText);
}
break;
case XPathResultType.String:
arg = new Function(Function.FunctionType.FuncString, arg);
break;
case XPathResultType.Number:
arg = new Function(Function.FunctionType.FuncNumber, arg);
break;
case XPathResultType.Boolean:
arg = new Function(Function.FunctionType.FuncBoolean, arg);
break;
}
argList[i] = arg;
}
}
}
return new Function(pi.FType, argList);
}
}
return new Function(prefix, name, argList);
}
// --------------- Pattern Parsing ----------------------
//>> Pattern ::= ( Pattern '|' )? LocationPathPattern
private AstNode ParsePattern()
{
AstNode opnd = ParseLocationPathPattern();
do
{
if (this.scanner.Kind != XPathScanner.LexKind.Union)
{
return opnd;
}
NextLex();
opnd = new Operator(Operator.Op.UNION, opnd, ParseLocationPathPattern());
} while (true);
}
//>> LocationPathPattern ::= '/' | RelativePathPattern | '//' RelativePathPattern | '/' RelativePathPattern
//>> | IdKeyPattern (('/' | '//') RelativePathPattern)?
private AstNode ParseLocationPathPattern()
{
AstNode opnd = null;
switch (this.scanner.Kind)
{
case XPathScanner.LexKind.Slash:
NextLex();
opnd = new Root();
if (this.scanner.Kind == XPathScanner.LexKind.Eof || this.scanner.Kind == XPathScanner.LexKind.Union)
{
return opnd;
}
break;
case XPathScanner.LexKind.SlashSlash:
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, new Root());
break;
case XPathScanner.LexKind.Name:
if (this.scanner.CanBeFunction)
{
opnd = ParseIdKeyPattern();
if (opnd != null)
{
switch (this.scanner.Kind)
{
case XPathScanner.LexKind.Slash:
NextLex();
break;
case XPathScanner.LexKind.SlashSlash:
NextLex();
opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd);
break;
default:
return opnd;
}
}
}
break;
}
return ParseRelativePathPattern(opnd);
}
//>> IdKeyPattern ::= 'id' '(' Literal ')' | 'key' '(' Literal ',' Literal ')'
private AstNode ParseIdKeyPattern()
{
Debug.Assert(this.scanner.CanBeFunction);
List<AstNode> argList = new List<AstNode>();
if (this.scanner.Prefix.Length == 0)
{
if (this.scanner.Name == "id")
{
ParamInfo pi = (ParamInfo)functionTable["id"];
NextLex();
PassToken(XPathScanner.LexKind.LParens);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(this.scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.RParens);
return new Function(pi.FType, argList);
}
if (this.scanner.Name == "key")
{
NextLex();
PassToken(XPathScanner.LexKind.LParens);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(this.scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.Comma);
CheckToken(XPathScanner.LexKind.String);
argList.Add(new Operand(this.scanner.StringValue));
NextLex();
PassToken(XPathScanner.LexKind.RParens);
return new Function("", "key", argList);
}
}
return null;
}
//>> PathOp ::= '/' | '//'
//>> RelativePathPattern ::= ( RelativePathPattern PathOp )? StepPattern
private AstNode ParseRelativePathPattern(AstNode qyInput)
{
AstNode opnd = ParseStepPattern(qyInput);
if (XPathScanner.LexKind.SlashSlash == this.scanner.Kind)
{
NextLex();
opnd = ParseRelativePathPattern(new Axis(Axis.AxisType.DescendantOrSelf, opnd));
}
else if (XPathScanner.LexKind.Slash == this.scanner.Kind)
{
NextLex();
opnd = ParseRelativePathPattern(opnd);
}
return opnd;
}
//>> StepPattern ::= ChildOrAttributeAxisSpecifier NodeTest Predicate*
//>> ChildOrAttributeAxisSpecifier ::= @ ? | ('child' | 'attribute') '::'
private AstNode ParseStepPattern(AstNode qyInput)
{
AstNode opnd;
Axis.AxisType axisType = Axis.AxisType.Child;
switch (this.scanner.Kind)
{
case XPathScanner.LexKind.At: //>> '@'
axisType = Axis.AxisType.Attribute;
NextLex();
break;
case XPathScanner.LexKind.Axe: //>> AxisName '::'
axisType = GetAxis();
if (axisType != Axis.AxisType.Child && axisType != Axis.AxisType.Attribute)
{
throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText);
}
NextLex();
break;
}
XPathNodeType nodeType = (
axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute :
/* default: */ XPathNodeType.Element
);
opnd = ParseNodeTest(qyInput, axisType, nodeType);
while (XPathScanner.LexKind.LBracket == this.scanner.Kind)
{
opnd = new Filter(opnd, ParsePredicate(opnd));
}
return opnd;
}
// --------------- Helper methods ----------------------
void CheckToken(XPathScanner.LexKind t)
{
if (this.scanner.Kind != t)
{
throw XPathException.Create(SR.Xp_InvalidToken, this.scanner.SourceText);
}
}
void PassToken(XPathScanner.LexKind t)
{
CheckToken(t);
NextLex();
}
void NextLex()
{
this.scanner.NextLex();
}
private bool TestOp(string op)
{
return (
this.scanner.Kind == XPathScanner.LexKind.Name &&
this.scanner.Prefix.Length == 0 &&
this.scanner.Name.Equals(op)
);
}
void CheckNodeSet(XPathResultType t)
{
if (t != XPathResultType.NodeSet && t != XPathResultType.Any)
{
throw XPathException.Create(SR.Xp_NodeSetExpected, this.scanner.SourceText);
}
}
// ----------------------------------------------------------------
static readonly XPathResultType[] temparray1 = { };
static readonly XPathResultType[] temparray2 = { XPathResultType.NodeSet };
static readonly XPathResultType[] temparray3 = { XPathResultType.Any };
static readonly XPathResultType[] temparray4 = { XPathResultType.String };
static readonly XPathResultType[] temparray5 = { XPathResultType.String, XPathResultType.String };
static readonly XPathResultType[] temparray6 = { XPathResultType.String, XPathResultType.Number, XPathResultType.Number };
static readonly XPathResultType[] temparray7 = { XPathResultType.String, XPathResultType.String, XPathResultType.String };
static readonly XPathResultType[] temparray8 = { XPathResultType.Boolean };
static readonly XPathResultType[] temparray9 = { XPathResultType.Number };
private class ParamInfo
{
private Function.FunctionType ftype;
private int minargs;
private int maxargs;
private XPathResultType[] argTypes;
public Function.FunctionType FType { get { return this.ftype; } }
public int Minargs { get { return this.minargs; } }
public int Maxargs { get { return this.maxargs; } }
public XPathResultType[] ArgTypes { get { return this.argTypes; } }
internal ParamInfo(Function.FunctionType ftype, int minargs, int maxargs, XPathResultType[] argTypes)
{
this.ftype = ftype;
this.minargs = minargs;
this.maxargs = maxargs;
this.argTypes = argTypes;
}
} //ParamInfo
private static Dictionary<string, ParamInfo> functionTable = CreateFunctionTable();
private static Dictionary<string, ParamInfo> CreateFunctionTable()
{
Dictionary<string, ParamInfo> table = new Dictionary<string, ParamInfo>(36);
table.Add("last", new ParamInfo(Function.FunctionType.FuncLast, 0, 0, temparray1));
table.Add("position", new ParamInfo(Function.FunctionType.FuncPosition, 0, 0, temparray1));
table.Add("name", new ParamInfo(Function.FunctionType.FuncName, 0, 1, temparray2));
table.Add("namespace-uri", new ParamInfo(Function.FunctionType.FuncNameSpaceUri, 0, 1, temparray2));
table.Add("local-name", new ParamInfo(Function.FunctionType.FuncLocalName, 0, 1, temparray2));
table.Add("count", new ParamInfo(Function.FunctionType.FuncCount, 1, 1, temparray2));
table.Add("id", new ParamInfo(Function.FunctionType.FuncID, 1, 1, temparray3));
table.Add("string", new ParamInfo(Function.FunctionType.FuncString, 0, 1, temparray3));
table.Add("concat", new ParamInfo(Function.FunctionType.FuncConcat, 2, 100, temparray4));
table.Add("starts-with", new ParamInfo(Function.FunctionType.FuncStartsWith, 2, 2, temparray5));
table.Add("contains", new ParamInfo(Function.FunctionType.FuncContains, 2, 2, temparray5));
table.Add("substring-before", new ParamInfo(Function.FunctionType.FuncSubstringBefore, 2, 2, temparray5));
table.Add("substring-after", new ParamInfo(Function.FunctionType.FuncSubstringAfter, 2, 2, temparray5));
table.Add("substring", new ParamInfo(Function.FunctionType.FuncSubstring, 2, 3, temparray6));
table.Add("string-length", new ParamInfo(Function.FunctionType.FuncStringLength, 0, 1, temparray4));
table.Add("normalize-space", new ParamInfo(Function.FunctionType.FuncNormalize, 0, 1, temparray4));
table.Add("translate", new ParamInfo(Function.FunctionType.FuncTranslate, 3, 3, temparray7));
table.Add("boolean", new ParamInfo(Function.FunctionType.FuncBoolean, 1, 1, temparray3));
table.Add("not", new ParamInfo(Function.FunctionType.FuncNot, 1, 1, temparray8));
table.Add("true", new ParamInfo(Function.FunctionType.FuncTrue, 0, 0, temparray8));
table.Add("false", new ParamInfo(Function.FunctionType.FuncFalse, 0, 0, temparray8));
table.Add("lang", new ParamInfo(Function.FunctionType.FuncLang, 1, 1, temparray4));
table.Add("number", new ParamInfo(Function.FunctionType.FuncNumber, 0, 1, temparray3));
table.Add("sum", new ParamInfo(Function.FunctionType.FuncSum, 1, 1, temparray2));
table.Add("floor", new ParamInfo(Function.FunctionType.FuncFloor, 1, 1, temparray9));
table.Add("ceiling", new ParamInfo(Function.FunctionType.FuncCeiling, 1, 1, temparray9));
table.Add("round", new ParamInfo(Function.FunctionType.FuncRound, 1, 1, temparray9));
return table;
}
private static Dictionary<string, Axis.AxisType> AxesTable = CreateAxesTable();
private static Dictionary<string, Axis.AxisType> CreateAxesTable()
{
Dictionary<string, Axis.AxisType> table = new Dictionary<string, Axis.AxisType>(13);
table.Add("ancestor", Axis.AxisType.Ancestor);
table.Add("ancestor-or-self", Axis.AxisType.AncestorOrSelf);
table.Add("attribute", Axis.AxisType.Attribute);
table.Add("child", Axis.AxisType.Child);
table.Add("descendant", Axis.AxisType.Descendant);
table.Add("descendant-or-self", Axis.AxisType.DescendantOrSelf);
table.Add("following", Axis.AxisType.Following);
table.Add("following-sibling", Axis.AxisType.FollowingSibling);
table.Add("namespace", Axis.AxisType.Namespace);
table.Add("parent", Axis.AxisType.Parent);
table.Add("preceding", Axis.AxisType.Preceding);
table.Add("preceding-sibling", Axis.AxisType.PrecedingSibling);
table.Add("self", Axis.AxisType.Self);
return table;
}
private Axis.AxisType GetAxis()
{
Debug.Assert(scanner.Kind == XPathScanner.LexKind.Axe);
Axis.AxisType axis;
if (!AxesTable.TryGetValue(scanner.Name, out axis))
{
throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText);
}
return axis;
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="GlobalLB.WideIPV2Binding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBWideIPID))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBPoolID))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBWideIPV2WideIPStatistics))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonObjectStatus))]
public partial class GlobalLBWideIPV2 : iControlInterface {
public GlobalLBWideIPV2() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_alias
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void add_alias(
GlobalLBWideIPID [] wide_ips,
string [] [] aliases
) {
this.Invoke("add_alias", new object [] {
wide_ips,
aliases});
}
public System.IAsyncResult Beginadd_alias(GlobalLBWideIPID [] wide_ips,string [] [] aliases, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_alias", new object[] {
wide_ips,
aliases}, callback, asyncState);
}
public void Endadd_alias(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_metadata
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void add_metadata(
GlobalLBWideIPID [] wide_ips,
string [] [] names,
string [] [] values
) {
this.Invoke("add_metadata", new object [] {
wide_ips,
names,
values});
}
public System.IAsyncResult Beginadd_metadata(GlobalLBWideIPID [] wide_ips,string [] [] names,string [] [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_metadata", new object[] {
wide_ips,
names,
values}, callback, asyncState);
}
public void Endadd_metadata(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_wide_ip_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void add_wide_ip_pool(
GlobalLBWideIPID [] wide_ips,
GlobalLBPoolID [] [] wide_ip_pools,
long [] [] orders,
long [] [] ratios
) {
this.Invoke("add_wide_ip_pool", new object [] {
wide_ips,
wide_ip_pools,
orders,
ratios});
}
public System.IAsyncResult Beginadd_wide_ip_pool(GlobalLBWideIPID [] wide_ips,GlobalLBPoolID [] [] wide_ip_pools,long [] [] orders,long [] [] ratios, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_wide_ip_pool", new object[] {
wide_ips,
wide_ip_pools,
orders,
ratios}, callback, asyncState);
}
public void Endadd_wide_ip_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_wide_ip_rule
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void add_wide_ip_rule(
GlobalLBWideIPID [] wide_ips,
string [] [] wide_ip_rules,
long [] [] priorities
) {
this.Invoke("add_wide_ip_rule", new object [] {
wide_ips,
wide_ip_rules,
priorities});
}
public System.IAsyncResult Beginadd_wide_ip_rule(GlobalLBWideIPID [] wide_ips,string [] [] wide_ip_rules,long [] [] priorities, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_wide_ip_rule", new object[] {
wide_ips,
wide_ip_rules,
priorities}, callback, asyncState);
}
public void Endadd_wide_ip_rule(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void create(
GlobalLBWideIPID [] wide_ips,
GlobalLBLBMethod [] lb_methods
) {
this.Invoke("create", new object [] {
wide_ips,
lb_methods});
}
public System.IAsyncResult Begincreate(GlobalLBWideIPID [] wide_ips,GlobalLBLBMethod [] lb_methods, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
wide_ips,
lb_methods}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_wide_ips
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void delete_all_wide_ips(
) {
this.Invoke("delete_all_wide_ips", new object [0]);
}
public System.IAsyncResult Begindelete_all_wide_ips(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_wide_ips", new object[0], callback, asyncState);
}
public void Enddelete_all_wide_ips(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_wide_ip
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void delete_wide_ip(
GlobalLBWideIPID [] wide_ips
) {
this.Invoke("delete_wide_ip", new object [] {
wide_ips});
}
public System.IAsyncResult Begindelete_wide_ip(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_wide_ip", new object[] {
wide_ips}, callback, asyncState);
}
public void Enddelete_wide_ip(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_alias
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_alias(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_alias", new object [] {
wide_ips});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_alias(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_alias", new object[] {
wide_ips}, callback, asyncState);
}
public string [] [] Endget_alias(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public GlobalLBWideIPV2WideIPStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((GlobalLBWideIPV2WideIPStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public GlobalLBWideIPV2WideIPStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((GlobalLBWideIPV2WideIPStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_description", new object [] {
wide_ips});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
wide_ips}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_enabled_state(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_enabled_state", new object [] {
wide_ips});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_enabled_state(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_enabled_state", new object[] {
wide_ips}, callback, asyncState);
}
public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_failure_response_return_code
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public GlobalLBDNSReturnCode [] get_failure_response_return_code(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_failure_response_return_code", new object [] {
wide_ips});
return ((GlobalLBDNSReturnCode [])(results[0]));
}
public System.IAsyncResult Beginget_failure_response_return_code(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_failure_response_return_code", new object[] {
wide_ips}, callback, asyncState);
}
public GlobalLBDNSReturnCode [] Endget_failure_response_return_code(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((GlobalLBDNSReturnCode [])(results[0]));
}
//-----------------------------------------------------------------------
// get_failure_response_return_code_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_failure_response_return_code_state(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_failure_response_return_code_state", new object [] {
wide_ips});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_failure_response_return_code_state(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_failure_response_return_code_state", new object[] {
wide_ips}, callback, asyncState);
}
public CommonEnabledState [] Endget_failure_response_return_code_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_failure_response_return_code_ttl
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_failure_response_return_code_ttl(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_failure_response_return_code_ttl", new object [] {
wide_ips});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_failure_response_return_code_ttl(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_failure_response_return_code_ttl", new object[] {
wide_ips}, callback, asyncState);
}
public long [] Endget_failure_response_return_code_ttl(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_last_resort_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public GlobalLBPoolID [] get_last_resort_pool(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_last_resort_pool", new object [] {
wide_ips});
return ((GlobalLBPoolID [])(results[0]));
}
public System.IAsyncResult Beginget_last_resort_pool(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_last_resort_pool", new object[] {
wide_ips}, callback, asyncState);
}
public GlobalLBPoolID [] Endget_last_resort_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((GlobalLBPoolID [])(results[0]));
}
//-----------------------------------------------------------------------
// get_lb_decision_log_verbosity
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public GlobalLBLBDecisionLogVerbosity [] [] get_lb_decision_log_verbosity(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_lb_decision_log_verbosity", new object [] {
wide_ips});
return ((GlobalLBLBDecisionLogVerbosity [] [])(results[0]));
}
public System.IAsyncResult Beginget_lb_decision_log_verbosity(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_lb_decision_log_verbosity", new object[] {
wide_ips}, callback, asyncState);
}
public GlobalLBLBDecisionLogVerbosity [] [] Endget_lb_decision_log_verbosity(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((GlobalLBLBDecisionLogVerbosity [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_lb_method
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public GlobalLBLBMethod [] get_lb_method(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_lb_method", new object [] {
wide_ips});
return ((GlobalLBLBMethod [])(results[0]));
}
public System.IAsyncResult Beginget_lb_method(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_lb_method", new object[] {
wide_ips}, callback, asyncState);
}
public GlobalLBLBMethod [] Endget_lb_method(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((GlobalLBLBMethod [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public GlobalLBWideIPID [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((GlobalLBWideIPID [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public GlobalLBWideIPID [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((GlobalLBWideIPID [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list_by_type
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public GlobalLBWideIPID [] [] get_list_by_type(
GlobalLBGTMQueryType [] types
) {
object [] results = this.Invoke("get_list_by_type", new object [] {
types});
return ((GlobalLBWideIPID [] [])(results[0]));
}
public System.IAsyncResult Beginget_list_by_type(GlobalLBGTMQueryType [] types, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list_by_type", new object[] {
types}, callback, asyncState);
}
public GlobalLBWideIPID [] [] Endget_list_by_type(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((GlobalLBWideIPID [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_metadata
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_metadata(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_metadata", new object [] {
wide_ips});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_metadata(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_metadata", new object[] {
wide_ips}, callback, asyncState);
}
public string [] [] Endget_metadata(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_metadata_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_metadata_description(
GlobalLBWideIPID [] wide_ips,
string [] [] names
) {
object [] results = this.Invoke("get_metadata_description", new object [] {
wide_ips,
names});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_metadata_description(GlobalLBWideIPID [] wide_ips,string [] [] names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_metadata_description", new object[] {
wide_ips,
names}, callback, asyncState);
}
public string [] [] Endget_metadata_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_metadata_persistence
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonMetadataPersistence [] [] get_metadata_persistence(
GlobalLBWideIPID [] wide_ips,
string [] [] names
) {
object [] results = this.Invoke("get_metadata_persistence", new object [] {
wide_ips,
names});
return ((CommonMetadataPersistence [] [])(results[0]));
}
public System.IAsyncResult Beginget_metadata_persistence(GlobalLBWideIPID [] wide_ips,string [] [] names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_metadata_persistence", new object[] {
wide_ips,
names}, callback, asyncState);
}
public CommonMetadataPersistence [] [] Endget_metadata_persistence(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonMetadataPersistence [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_metadata_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_metadata_value(
GlobalLBWideIPID [] wide_ips,
string [] [] names
) {
object [] results = this.Invoke("get_metadata_value", new object [] {
wide_ips,
names});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_metadata_value(GlobalLBWideIPID [] wide_ips,string [] [] names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_metadata_value", new object[] {
wide_ips,
names}, callback, asyncState);
}
public string [] [] Endget_metadata_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_minimal_response_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_minimal_response_state(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_minimal_response_state", new object [] {
wide_ips});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_minimal_response_state(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_minimal_response_state", new object[] {
wide_ips}, callback, asyncState);
}
public CommonEnabledState [] Endget_minimal_response_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_object_status
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonObjectStatus [] get_object_status(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_object_status", new object [] {
wide_ips});
return ((CommonObjectStatus [])(results[0]));
}
public System.IAsyncResult Beginget_object_status(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_object_status", new object[] {
wide_ips}, callback, asyncState);
}
public CommonObjectStatus [] Endget_object_status(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonObjectStatus [])(results[0]));
}
//-----------------------------------------------------------------------
// get_persistence_cidr_ipv4
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_persistence_cidr_ipv4(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_persistence_cidr_ipv4", new object [] {
wide_ips});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_persistence_cidr_ipv4(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_persistence_cidr_ipv4", new object[] {
wide_ips}, callback, asyncState);
}
public long [] Endget_persistence_cidr_ipv4(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_persistence_cidr_ipv6
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_persistence_cidr_ipv6(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_persistence_cidr_ipv6", new object [] {
wide_ips});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_persistence_cidr_ipv6(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_persistence_cidr_ipv6", new object[] {
wide_ips}, callback, asyncState);
}
public long [] Endget_persistence_cidr_ipv6(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_persistence_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_persistence_state(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_persistence_state", new object [] {
wide_ips});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_persistence_state(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_persistence_state", new object[] {
wide_ips}, callback, asyncState);
}
public CommonEnabledState [] Endget_persistence_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_persistence_ttl
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_persistence_ttl(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_persistence_ttl", new object [] {
wide_ips});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_persistence_ttl(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_persistence_ttl", new object[] {
wide_ips}, callback, asyncState);
}
public long [] Endget_persistence_ttl(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public GlobalLBWideIPV2WideIPStatistics get_statistics(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_statistics", new object [] {
wide_ips});
return ((GlobalLBWideIPV2WideIPStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
wide_ips}, callback, asyncState);
}
public GlobalLBWideIPV2WideIPStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((GlobalLBWideIPV2WideIPStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_wide_ip
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public GlobalLBWideIPID [] [] get_wide_ip(
string [] aliases
) {
object [] results = this.Invoke("get_wide_ip", new object [] {
aliases});
return ((GlobalLBWideIPID [] [])(results[0]));
}
public System.IAsyncResult Beginget_wide_ip(string [] aliases, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_wide_ip", new object[] {
aliases}, callback, asyncState);
}
public GlobalLBWideIPID [] [] Endget_wide_ip(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((GlobalLBWideIPID [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_wide_ip_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public GlobalLBPoolID [] [] get_wide_ip_pool(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_wide_ip_pool", new object [] {
wide_ips});
return ((GlobalLBPoolID [] [])(results[0]));
}
public System.IAsyncResult Beginget_wide_ip_pool(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_wide_ip_pool", new object[] {
wide_ips}, callback, asyncState);
}
public GlobalLBPoolID [] [] Endget_wide_ip_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((GlobalLBPoolID [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_wide_ip_pool_order
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_wide_ip_pool_order(
GlobalLBWideIPID [] wide_ips,
GlobalLBPoolID [] [] wide_ip_pools
) {
object [] results = this.Invoke("get_wide_ip_pool_order", new object [] {
wide_ips,
wide_ip_pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_wide_ip_pool_order(GlobalLBWideIPID [] wide_ips,GlobalLBPoolID [] [] wide_ip_pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_wide_ip_pool_order", new object[] {
wide_ips,
wide_ip_pools}, callback, asyncState);
}
public long [] [] Endget_wide_ip_pool_order(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_wide_ip_pool_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_wide_ip_pool_ratio(
GlobalLBWideIPID [] wide_ips,
GlobalLBPoolID [] [] wide_ip_pools
) {
object [] results = this.Invoke("get_wide_ip_pool_ratio", new object [] {
wide_ips,
wide_ip_pools});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_wide_ip_pool_ratio(GlobalLBWideIPID [] wide_ips,GlobalLBPoolID [] [] wide_ip_pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_wide_ip_pool_ratio", new object[] {
wide_ips,
wide_ip_pools}, callback, asyncState);
}
public long [] [] Endget_wide_ip_pool_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_wide_ip_rule
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_wide_ip_rule(
GlobalLBWideIPID [] wide_ips
) {
object [] results = this.Invoke("get_wide_ip_rule", new object [] {
wide_ips});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_wide_ip_rule(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_wide_ip_rule", new object[] {
wide_ips}, callback, asyncState);
}
public string [] [] Endget_wide_ip_rule(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_wide_ip_rule_priority
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] [] get_wide_ip_rule_priority(
GlobalLBWideIPID [] wide_ips,
string [] [] wide_ip_rules
) {
object [] results = this.Invoke("get_wide_ip_rule_priority", new object [] {
wide_ips,
wide_ip_rules});
return ((long [] [])(results[0]));
}
public System.IAsyncResult Beginget_wide_ip_rule_priority(GlobalLBWideIPID [] wide_ips,string [] [] wide_ip_rules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_wide_ip_rule_priority", new object[] {
wide_ips,
wide_ip_rules}, callback, asyncState);
}
public long [] [] Endget_wide_ip_rule_priority(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [] [])(results[0]));
}
//-----------------------------------------------------------------------
// remove_alias
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void remove_alias(
GlobalLBWideIPID [] wide_ips,
string [] [] aliases
) {
this.Invoke("remove_alias", new object [] {
wide_ips,
aliases});
}
public System.IAsyncResult Beginremove_alias(GlobalLBWideIPID [] wide_ips,string [] [] aliases, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_alias", new object[] {
wide_ips,
aliases}, callback, asyncState);
}
public void Endremove_alias(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_aliases
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void remove_all_aliases(
GlobalLBWideIPID [] wide_ips
) {
this.Invoke("remove_all_aliases", new object [] {
wide_ips});
}
public System.IAsyncResult Beginremove_all_aliases(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_aliases", new object[] {
wide_ips}, callback, asyncState);
}
public void Endremove_all_aliases(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_metadata
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void remove_all_metadata(
GlobalLBWideIPID [] wide_ips
) {
this.Invoke("remove_all_metadata", new object [] {
wide_ips});
}
public System.IAsyncResult Beginremove_all_metadata(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_metadata", new object[] {
wide_ips}, callback, asyncState);
}
public void Endremove_all_metadata(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_wide_ip_pools
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void remove_all_wide_ip_pools(
GlobalLBWideIPID [] wide_ips
) {
this.Invoke("remove_all_wide_ip_pools", new object [] {
wide_ips});
}
public System.IAsyncResult Beginremove_all_wide_ip_pools(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_wide_ip_pools", new object[] {
wide_ips}, callback, asyncState);
}
public void Endremove_all_wide_ip_pools(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_wide_ip_rules
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void remove_all_wide_ip_rules(
GlobalLBWideIPID [] wide_ips
) {
this.Invoke("remove_all_wide_ip_rules", new object [] {
wide_ips});
}
public System.IAsyncResult Beginremove_all_wide_ip_rules(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_wide_ip_rules", new object[] {
wide_ips}, callback, asyncState);
}
public void Endremove_all_wide_ip_rules(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_metadata
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void remove_metadata(
GlobalLBWideIPID [] wide_ips,
string [] [] names
) {
this.Invoke("remove_metadata", new object [] {
wide_ips,
names});
}
public System.IAsyncResult Beginremove_metadata(GlobalLBWideIPID [] wide_ips,string [] [] names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_metadata", new object[] {
wide_ips,
names}, callback, asyncState);
}
public void Endremove_metadata(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_wide_ip_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void remove_wide_ip_pool(
GlobalLBWideIPID [] wide_ips,
GlobalLBPoolID [] [] wide_ip_pools
) {
this.Invoke("remove_wide_ip_pool", new object [] {
wide_ips,
wide_ip_pools});
}
public System.IAsyncResult Beginremove_wide_ip_pool(GlobalLBWideIPID [] wide_ips,GlobalLBPoolID [] [] wide_ip_pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_wide_ip_pool", new object[] {
wide_ips,
wide_ip_pools}, callback, asyncState);
}
public void Endremove_wide_ip_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_wide_ip_rule
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void remove_wide_ip_rule(
GlobalLBWideIPID [] wide_ips,
string [] [] wide_ip_rules
) {
this.Invoke("remove_wide_ip_rule", new object [] {
wide_ips,
wide_ip_rules});
}
public System.IAsyncResult Beginremove_wide_ip_rule(GlobalLBWideIPID [] wide_ips,string [] [] wide_ip_rules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_wide_ip_rule", new object[] {
wide_ips,
wide_ip_rules}, callback, asyncState);
}
public void Endremove_wide_ip_rule(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void reset_statistics(
GlobalLBWideIPID [] wide_ips
) {
this.Invoke("reset_statistics", new object [] {
wide_ips});
}
public System.IAsyncResult Beginreset_statistics(GlobalLBWideIPID [] wide_ips, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
wide_ips}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_description(
GlobalLBWideIPID [] wide_ips,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
wide_ips,
descriptions});
}
public System.IAsyncResult Beginset_description(GlobalLBWideIPID [] wide_ips,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
wide_ips,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_enabled_state(
GlobalLBWideIPID [] wide_ips,
CommonEnabledState [] states
) {
this.Invoke("set_enabled_state", new object [] {
wide_ips,
states});
}
public System.IAsyncResult Beginset_enabled_state(GlobalLBWideIPID [] wide_ips,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_enabled_state", new object[] {
wide_ips,
states}, callback, asyncState);
}
public void Endset_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_failure_response_return_code
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_failure_response_return_code(
GlobalLBWideIPID [] wide_ips,
GlobalLBDNSReturnCode [] return_codes
) {
this.Invoke("set_failure_response_return_code", new object [] {
wide_ips,
return_codes});
}
public System.IAsyncResult Beginset_failure_response_return_code(GlobalLBWideIPID [] wide_ips,GlobalLBDNSReturnCode [] return_codes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_failure_response_return_code", new object[] {
wide_ips,
return_codes}, callback, asyncState);
}
public void Endset_failure_response_return_code(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_failure_response_return_code_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_failure_response_return_code_state(
GlobalLBWideIPID [] wide_ips,
CommonEnabledState [] states
) {
this.Invoke("set_failure_response_return_code_state", new object [] {
wide_ips,
states});
}
public System.IAsyncResult Beginset_failure_response_return_code_state(GlobalLBWideIPID [] wide_ips,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_failure_response_return_code_state", new object[] {
wide_ips,
states}, callback, asyncState);
}
public void Endset_failure_response_return_code_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_failure_response_return_code_ttl
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_failure_response_return_code_ttl(
GlobalLBWideIPID [] wide_ips,
long [] values
) {
this.Invoke("set_failure_response_return_code_ttl", new object [] {
wide_ips,
values});
}
public System.IAsyncResult Beginset_failure_response_return_code_ttl(GlobalLBWideIPID [] wide_ips,long [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_failure_response_return_code_ttl", new object[] {
wide_ips,
values}, callback, asyncState);
}
public void Endset_failure_response_return_code_ttl(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_last_resort_pool
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_last_resort_pool(
GlobalLBWideIPID [] wide_ips,
GlobalLBPoolID [] pools
) {
this.Invoke("set_last_resort_pool", new object [] {
wide_ips,
pools});
}
public System.IAsyncResult Beginset_last_resort_pool(GlobalLBWideIPID [] wide_ips,GlobalLBPoolID [] pools, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_last_resort_pool", new object[] {
wide_ips,
pools}, callback, asyncState);
}
public void Endset_last_resort_pool(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_lb_decision_log_verbosity
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_lb_decision_log_verbosity(
GlobalLBWideIPID [] wide_ips,
GlobalLBLBDecisionLogVerbosity [] [] verbosities
) {
this.Invoke("set_lb_decision_log_verbosity", new object [] {
wide_ips,
verbosities});
}
public System.IAsyncResult Beginset_lb_decision_log_verbosity(GlobalLBWideIPID [] wide_ips,GlobalLBLBDecisionLogVerbosity [] [] verbosities, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_lb_decision_log_verbosity", new object[] {
wide_ips,
verbosities}, callback, asyncState);
}
public void Endset_lb_decision_log_verbosity(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_lb_method
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_lb_method(
GlobalLBWideIPID [] wide_ips,
GlobalLBLBMethod [] lb_methods
) {
this.Invoke("set_lb_method", new object [] {
wide_ips,
lb_methods});
}
public System.IAsyncResult Beginset_lb_method(GlobalLBWideIPID [] wide_ips,GlobalLBLBMethod [] lb_methods, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_lb_method", new object[] {
wide_ips,
lb_methods}, callback, asyncState);
}
public void Endset_lb_method(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_metadata_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_metadata_description(
GlobalLBWideIPID [] wide_ips,
string [] [] names,
string [] [] descriptions
) {
this.Invoke("set_metadata_description", new object [] {
wide_ips,
names,
descriptions});
}
public System.IAsyncResult Beginset_metadata_description(GlobalLBWideIPID [] wide_ips,string [] [] names,string [] [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_metadata_description", new object[] {
wide_ips,
names,
descriptions}, callback, asyncState);
}
public void Endset_metadata_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_metadata_persistence
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_metadata_persistence(
GlobalLBWideIPID [] wide_ips,
string [] [] names,
CommonMetadataPersistence [] [] values
) {
this.Invoke("set_metadata_persistence", new object [] {
wide_ips,
names,
values});
}
public System.IAsyncResult Beginset_metadata_persistence(GlobalLBWideIPID [] wide_ips,string [] [] names,CommonMetadataPersistence [] [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_metadata_persistence", new object[] {
wide_ips,
names,
values}, callback, asyncState);
}
public void Endset_metadata_persistence(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_metadata_value
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_metadata_value(
GlobalLBWideIPID [] wide_ips,
string [] [] names,
string [] [] values
) {
this.Invoke("set_metadata_value", new object [] {
wide_ips,
names,
values});
}
public System.IAsyncResult Beginset_metadata_value(GlobalLBWideIPID [] wide_ips,string [] [] names,string [] [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_metadata_value", new object[] {
wide_ips,
names,
values}, callback, asyncState);
}
public void Endset_metadata_value(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_minimal_response_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_minimal_response_state(
GlobalLBWideIPID [] wide_ips,
CommonEnabledState [] states
) {
this.Invoke("set_minimal_response_state", new object [] {
wide_ips,
states});
}
public System.IAsyncResult Beginset_minimal_response_state(GlobalLBWideIPID [] wide_ips,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_minimal_response_state", new object[] {
wide_ips,
states}, callback, asyncState);
}
public void Endset_minimal_response_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_persistence_cidr_ipv4
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_persistence_cidr_ipv4(
GlobalLBWideIPID [] wide_ips,
long [] values
) {
this.Invoke("set_persistence_cidr_ipv4", new object [] {
wide_ips,
values});
}
public System.IAsyncResult Beginset_persistence_cidr_ipv4(GlobalLBWideIPID [] wide_ips,long [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_persistence_cidr_ipv4", new object[] {
wide_ips,
values}, callback, asyncState);
}
public void Endset_persistence_cidr_ipv4(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_persistence_cidr_ipv6
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_persistence_cidr_ipv6(
GlobalLBWideIPID [] wide_ips,
long [] values
) {
this.Invoke("set_persistence_cidr_ipv6", new object [] {
wide_ips,
values});
}
public System.IAsyncResult Beginset_persistence_cidr_ipv6(GlobalLBWideIPID [] wide_ips,long [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_persistence_cidr_ipv6", new object[] {
wide_ips,
values}, callback, asyncState);
}
public void Endset_persistence_cidr_ipv6(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_persistence_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_persistence_state(
GlobalLBWideIPID [] wide_ips,
CommonEnabledState [] states
) {
this.Invoke("set_persistence_state", new object [] {
wide_ips,
states});
}
public System.IAsyncResult Beginset_persistence_state(GlobalLBWideIPID [] wide_ips,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_persistence_state", new object[] {
wide_ips,
states}, callback, asyncState);
}
public void Endset_persistence_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_persistence_ttl
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_persistence_ttl(
GlobalLBWideIPID [] wide_ips,
long [] values
) {
this.Invoke("set_persistence_ttl", new object [] {
wide_ips,
values});
}
public System.IAsyncResult Beginset_persistence_ttl(GlobalLBWideIPID [] wide_ips,long [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_persistence_ttl", new object[] {
wide_ips,
values}, callback, asyncState);
}
public void Endset_persistence_ttl(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_wide_ip_pool_order
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_wide_ip_pool_order(
GlobalLBWideIPID [] wide_ips,
GlobalLBPoolID [] [] wide_ip_pools,
long [] [] orders
) {
this.Invoke("set_wide_ip_pool_order", new object [] {
wide_ips,
wide_ip_pools,
orders});
}
public System.IAsyncResult Beginset_wide_ip_pool_order(GlobalLBWideIPID [] wide_ips,GlobalLBPoolID [] [] wide_ip_pools,long [] [] orders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_wide_ip_pool_order", new object[] {
wide_ips,
wide_ip_pools,
orders}, callback, asyncState);
}
public void Endset_wide_ip_pool_order(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_wide_ip_pool_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_wide_ip_pool_ratio(
GlobalLBWideIPID [] wide_ips,
GlobalLBPoolID [] [] wide_ip_pools,
long [] [] ratios
) {
this.Invoke("set_wide_ip_pool_ratio", new object [] {
wide_ips,
wide_ip_pools,
ratios});
}
public System.IAsyncResult Beginset_wide_ip_pool_ratio(GlobalLBWideIPID [] wide_ips,GlobalLBPoolID [] [] wide_ip_pools,long [] [] ratios, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_wide_ip_pool_ratio", new object[] {
wide_ips,
wide_ip_pools,
ratios}, callback, asyncState);
}
public void Endset_wide_ip_pool_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_wide_ip_rule_priority
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/WideIPV2",
RequestNamespace="urn:iControl:GlobalLB/WideIPV2", ResponseNamespace="urn:iControl:GlobalLB/WideIPV2")]
public void set_wide_ip_rule_priority(
GlobalLBWideIPID [] wide_ips,
string [] [] wide_ip_rules,
long [] [] priorities
) {
this.Invoke("set_wide_ip_rule_priority", new object [] {
wide_ips,
wide_ip_rules,
priorities});
}
public System.IAsyncResult Beginset_wide_ip_rule_priority(GlobalLBWideIPID [] wide_ips,string [] [] wide_ip_rules,long [] [] priorities, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_wide_ip_rule_priority", new object[] {
wide_ips,
wide_ip_rules,
priorities}, callback, asyncState);
}
public void Endset_wide_ip_rule_priority(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.WideIPV2.WideIPStatisticEntry", Namespace = "urn:iControl")]
public partial class GlobalLBWideIPV2WideIPStatisticEntry
{
private GlobalLBWideIPID wide_ipField;
public GlobalLBWideIPID wide_ip
{
get { return this.wide_ipField; }
set { this.wide_ipField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.WideIPV2.WideIPStatistics", Namespace = "urn:iControl")]
public partial class GlobalLBWideIPV2WideIPStatistics
{
private GlobalLBWideIPV2WideIPStatisticEntry [] statisticsField;
public GlobalLBWideIPV2WideIPStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
}
| |
// 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;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Benchmarks.Configuration;
using Benchmarks.Data;
using Benchmarks.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.PlatformAbstractions;
using Npgsql;
namespace Benchmarks
{
public class Startup
{
public Startup(IHostingEnvironment hostingEnv, Scenarios scenarios)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(PlatformServices.Default.Application.ApplicationBasePath)
.AddCommandLine(Program.Args)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{hostingEnv.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
Scenarios = scenarios;
}
public IConfigurationRoot Configuration { get; set; }
public Scenarios Scenarios { get; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration);
// We re-register the Scenarios as an instance singleton here to avoid it being created again due to the
// registration done in Program.Main
services.AddSingleton(Scenarios);
// Common DB services
services.AddSingleton<IRandom, DefaultRandom>();
services.AddSingleton<ApplicationDbSeeder>();
services.AddEntityFrameworkSqlServer()
.AddDbContext<ApplicationDbContext>();
if (Scenarios.Any("Raw") || Scenarios.Any("Dapper"))
{
services.AddSingleton<DbProviderFactory>((provider) => {
var settings = provider.GetRequiredService<IOptions<AppSettings>>().Value;
if (settings.Database == DatabaseServer.PostgreSql)
{
return NpgsqlFactory.Instance;
}
else
{
return SqlClientFactory.Instance;
}
});
}
if (Scenarios.Any("Ef"))
{
services.AddScoped<EfDb>();
}
if (Scenarios.Any("Raw"))
{
services.AddScoped<RawDb>();
}
if (Scenarios.Any("Dapper"))
{
services.AddScoped<DapperDb>();
}
if (Scenarios.Any("Fortunes"))
{
var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana);
settings.AllowCharacter('\u2014'); // allow EM DASH through
services.AddWebEncoders((options) =>
{
options.TextEncoderSettings = settings;
});
}
if (Scenarios.Any("Mvc"))
{
var mvcBuilder = services
.AddMvcCore()
//.AddApplicationPart(typeof(Startup).GetTypeInfo().Assembly)
.AddControllersAsServices();
if (Scenarios.MvcJson || Scenarios.Any("MvcDbSingle") || Scenarios.Any("MvcDbMulti"))
{
mvcBuilder.AddJsonFormatters();
}
if (Scenarios.MvcViews || Scenarios.Any("MvcDbFortunes"))
{
mvcBuilder
.AddViews()
.AddRazorViewEngine();
}
}
if (Scenarios.Any("MemoryCache"))
{
services.AddMemoryCache();
}
if (Scenarios.Any("ResponseCaching"))
{
services.AddMemoryResponseCacheStore();
}
return services.BuildServiceProvider(validateScopes: true);
}
public void Configure(IApplicationBuilder app, ApplicationDbSeeder dbSeeder)
{
if (Scenarios.Plaintext)
{
app.UsePlainText();
}
if (Scenarios.Json)
{
app.UseJson();
}
if (Scenarios.Copy)
{
app.UseCopyToAsync();
}
// Single query endpoints
if (Scenarios.DbSingleQueryRaw)
{
app.UseSingleQueryRaw();
}
if (Scenarios.DbSingleQueryDapper)
{
app.UseSingleQueryDapper();
}
if (Scenarios.DbSingleQueryEf)
{
app.UseSingleQueryEf();
}
// Multiple query endpoints
if (Scenarios.DbMultiQueryRaw)
{
app.UseMultipleQueriesRaw();
}
if (Scenarios.DbMultiQueryDapper)
{
app.UseMultipleQueriesDapper();
}
if (Scenarios.DbMultiQueryEf)
{
app.UseMultipleQueriesEf();
}
// Multiple update endpoints
if (Scenarios.DbMultiUpdateRaw)
{
app.UseMultipleUpdatesRaw();
}
if (Scenarios.DbMultiUpdateDapper)
{
app.UseMultipleUpdatesDapper();
}
if (Scenarios.DbMultiUpdateEf)
{
app.UseMultipleUpdatesEf();
}
// Fortunes endpoints
if (Scenarios.DbFortunesRaw)
{
app.UseFortunesRaw();
}
if (Scenarios.DbFortunesDapper)
{
app.UseFortunesDapper();
}
if (Scenarios.DbFortunesEf)
{
app.UseFortunesEf();
}
if (Scenarios.Any("Db"))
{
if (!dbSeeder.Seed())
{
Environment.Exit(1);
}
}
if (Scenarios.Any("Mvc"))
{
app.UseMvc();
}
if (Scenarios.StaticFiles)
{
app.UseStaticFiles();
}
if (Scenarios.Any("MemoryCachePlaintext"))
{
app.UseMemoryCachePlaintext();
}
if (Scenarios.ResponseCachingPlaintextCached)
{
app.UseResponseCachingPlaintextCached();
}
if (Scenarios.ResponseCachingPlaintextResponseNoCache)
{
app.UseResponseCachingPlaintextResponseNoCache();
}
if (Scenarios.ResponseCachingPlaintextRequestNoCache)
{
app.UseResponseCachingPlaintextRequestNoCache();
}
if (Scenarios.ResponseCachingPlaintextVaryByCached)
{
app.UseResponseCachingPlaintextVaryByCached();
}
app.RunDebugInfoPage();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.ComponentModel.DataAnnotations
{
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
[System.ObsoleteAttribute("This attribute is no longer in use and will be ignored if applied.")]
public sealed partial class AssociationAttribute : System.Attribute
{
public AssociationAttribute(string name, string thisKey, string otherKey) { }
public bool IsForeignKey { get { throw null; } set { } }
public string Name { get { throw null; } }
public string OtherKey { get { throw null; } }
public System.Collections.Generic.IEnumerable<string> OtherKeyMembers { get { throw null; } }
public string ThisKey { get { throw null; } }
public System.Collections.Generic.IEnumerable<string> ThisKeyMembers { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(128), AllowMultiple = false)]
public partial class CompareAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public CompareAttribute(string otherProperty) { }
public string OtherProperty { get { throw null; } }
public string OtherPropertyDisplayName { get { throw null; } }
public override bool RequiresValidationContext { get { throw null; } }
public override string FormatErrorMessage(string name) { throw null; }
protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class ConcurrencyCheckAttribute : System.Attribute
{
public ConcurrencyCheckAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class CreditCardAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public CreditCardAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2500), AllowMultiple = true)]
public sealed partial class CustomValidationAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public CustomValidationAttribute(System.Type validatorType, string method) { }
public string Method { get { throw null; } }
public System.Type ValidatorType { get { throw null; } }
public override string FormatErrorMessage(string name) { throw null; }
protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { throw null; }
}
public enum DataType
{
CreditCard = 14,
Currency = 6,
Custom = 0,
Date = 2,
DateTime = 1,
Duration = 4,
EmailAddress = 10,
Html = 8,
ImageUrl = 13,
MultilineText = 9,
Password = 11,
PhoneNumber = 5,
PostalCode = 15,
Text = 7,
Time = 3,
Upload = 16,
Url = 12,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]
public partial class DataTypeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public DataTypeAttribute(System.ComponentModel.DataAnnotations.DataType dataType) { }
public DataTypeAttribute(string customDataType) { }
public string CustomDataType { get { throw null; } }
public System.ComponentModel.DataAnnotations.DataType DataType { get { throw null; } }
public System.ComponentModel.DataAnnotations.DisplayFormatAttribute DisplayFormat { get { throw null; } protected set { } }
public virtual string GetDataTypeName() { throw null; }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]
public sealed partial class DisplayAttribute : System.Attribute
{
public DisplayAttribute() { }
public bool AutoGenerateField { get { throw null; } set { } }
public bool AutoGenerateFilter { get { throw null; } set { } }
public string Description { get { throw null; } set { } }
public string GroupName { get { throw null; } set { } }
public string Name { get { throw null; } set { } }
public int Order { get { throw null; } set { } }
public string Prompt { get { throw null; } set { } }
public System.Type ResourceType { get { throw null; } set { } }
public string ShortName { get { throw null; } set { } }
public System.Nullable<bool> GetAutoGenerateField() { throw null; }
public System.Nullable<bool> GetAutoGenerateFilter() { throw null; }
public string GetDescription() { throw null; }
public string GetGroupName() { throw null; }
public string GetName() { throw null; }
public System.Nullable<int> GetOrder() { throw null; }
public string GetPrompt() { throw null; }
public string GetShortName() { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited = true, AllowMultiple = false)]
public partial class DisplayColumnAttribute : System.Attribute
{
public DisplayColumnAttribute(string displayColumn) { }
public DisplayColumnAttribute(string displayColumn, string sortColumn) { }
public DisplayColumnAttribute(string displayColumn, string sortColumn, bool sortDescending) { }
public string DisplayColumn { get { throw null; } }
public string SortColumn { get { throw null; } }
public bool SortDescending { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class DisplayFormatAttribute : System.Attribute
{
public DisplayFormatAttribute() { }
public bool ApplyFormatInEditMode { get { throw null; } set { } }
public bool ConvertEmptyStringToNull { get { throw null; } set { } }
public string DataFormatString { get { throw null; } set { } }
public bool HtmlEncode { get { throw null; } set { } }
public string NullDisplayText { get { throw null; } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class EditableAttribute : System.Attribute
{
public EditableAttribute(bool allowEdit) { }
public bool AllowEdit { get { throw null; } }
public bool AllowInitialValue { get { throw null; } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class EmailAddressAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public EmailAddressAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]
public sealed partial class EnumDataTypeAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public EnumDataTypeAttribute(System.Type enumType) : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public System.Type EnumType { get { throw null; } }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class FileExtensionsAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public FileExtensionsAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public string Extensions { get { throw null; } set { } }
public override string FormatErrorMessage(string name) { throw null; }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
[System.ObsoleteAttribute("This attribute is no longer in use and will be ignored if applied.")]
public sealed partial class FilterUIHintAttribute : System.Attribute
{
public FilterUIHintAttribute(string filterUIHint) { }
public FilterUIHintAttribute(string filterUIHint, string presentationLayer) { }
public FilterUIHintAttribute(string filterUIHint, string presentationLayer, params object[] controlParameters) { }
public System.Collections.Generic.IDictionary<string, object> ControlParameters { get { throw null; } }
public string FilterUIHint { get { throw null; } }
public string PresentationLayer { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
}
public partial interface IValidatableObject
{
System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext);
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class KeyAttribute : System.Attribute
{
public KeyAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class MaxLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public MaxLengthAttribute() { }
public MaxLengthAttribute(int length) { }
public int Length { get { throw null; } }
public override string FormatErrorMessage(string name) { throw null; }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class MinLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public MinLengthAttribute(int length) { }
public int Length { get { throw null; } }
public override string FormatErrorMessage(string name) { throw null; }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class PhoneAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public PhoneAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class RangeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public RangeAttribute(double minimum, double maximum) { }
public RangeAttribute(int minimum, int maximum) { }
public RangeAttribute(System.Type type, string minimum, string maximum) { }
public object Maximum { get { throw null; } }
public object Minimum { get { throw null; } }
public System.Type OperandType { get { throw null; } }
public override string FormatErrorMessage(string name) { throw null; }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public RegularExpressionAttribute(string pattern) { }
public int MatchTimeoutInMilliseconds { get { throw null; } set { } }
public string Pattern { get { throw null; } }
public override string FormatErrorMessage(string name) { throw null; }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class RequiredAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public RequiredAttribute() { }
public bool AllowEmptyStrings { get { throw null; } set { } }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class ScaffoldColumnAttribute : System.Attribute
{
public ScaffoldColumnAttribute(bool scaffold) { }
public bool Scaffold { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class StringLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public StringLengthAttribute(int maximumLength) { }
public int MaximumLength { get { throw null; } }
public int MinimumLength { get { throw null; } set { } }
public override string FormatErrorMessage(string name) { throw null; }
public override bool IsValid(object value) { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class TimestampAttribute : System.Attribute
{
public TimestampAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = true)]
public partial class UIHintAttribute : System.Attribute
{
public UIHintAttribute(string uiHint) { }
public UIHintAttribute(string uiHint, string presentationLayer) { }
public UIHintAttribute(string uiHint, string presentationLayer, params object[] controlParameters) { }
public System.Collections.Generic.IDictionary<string, object> ControlParameters { get { throw null; } }
public string PresentationLayer { get { throw null; } }
public string UIHint { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class UrlAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public UrlAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { throw null; }
}
public abstract partial class ValidationAttribute : System.Attribute
{
protected ValidationAttribute() { }
protected ValidationAttribute(System.Func<string> errorMessageAccessor) { }
protected ValidationAttribute(string errorMessage) { }
public string ErrorMessage { get { throw null; } set { } }
public string ErrorMessageResourceName { get { throw null; } set { } }
public System.Type ErrorMessageResourceType { get { throw null; } set { } }
protected string ErrorMessageString { get { throw null; } }
public virtual bool RequiresValidationContext { get { throw null; } }
public virtual string FormatErrorMessage(string name) { throw null; }
public System.ComponentModel.DataAnnotations.ValidationResult GetValidationResult(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { throw null; }
public virtual bool IsValid(object value) { throw null; }
protected virtual System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { throw null; }
public void Validate(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { }
public void Validate(object value, string name) { }
}
public sealed partial class ValidationContext : System.IServiceProvider
{
public ValidationContext(object instance) { }
public ValidationContext(object instance, System.Collections.Generic.IDictionary<object, object> items) { }
public ValidationContext(object instance, System.IServiceProvider serviceProvider, System.Collections.Generic.IDictionary<object, object> items) { }
public string DisplayName { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<object, object> Items { get { throw null; } }
public string MemberName { get { throw null; } set { } }
public object ObjectInstance { get { throw null; } }
public System.Type ObjectType { get { throw null; } }
public object GetService(System.Type serviceType) { throw null; }
public void InitializeServiceProvider(System.Func<System.Type, object> serviceProvider) { }
}
public partial class ValidationException : System.Exception
{
public ValidationException() { }
public ValidationException(System.ComponentModel.DataAnnotations.ValidationResult validationResult, System.ComponentModel.DataAnnotations.ValidationAttribute validatingAttribute, object value) { }
public ValidationException(string message) { }
public ValidationException(string errorMessage, System.ComponentModel.DataAnnotations.ValidationAttribute validatingAttribute, object value) { }
public ValidationException(string message, System.Exception innerException) { }
protected ValidationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public System.ComponentModel.DataAnnotations.ValidationAttribute ValidationAttribute { get { throw null; } }
public System.ComponentModel.DataAnnotations.ValidationResult ValidationResult { get { throw null; } }
public object Value { get { throw null; } }
}
public partial class ValidationResult
{
public static readonly System.ComponentModel.DataAnnotations.ValidationResult Success;
protected ValidationResult(System.ComponentModel.DataAnnotations.ValidationResult validationResult) { }
public ValidationResult(string errorMessage) { }
public ValidationResult(string errorMessage, System.Collections.Generic.IEnumerable<string> memberNames) { }
public string ErrorMessage { get { throw null; } set { } }
public System.Collections.Generic.IEnumerable<string> MemberNames { get { throw null; } }
public override string ToString() { throw null; }
}
public static partial class Validator
{
public static bool TryValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults) { throw null; }
public static bool TryValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults, bool validateAllProperties) { throw null; }
public static bool TryValidateProperty(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults) { throw null; }
public static bool TryValidateValue(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults, System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationAttribute> validationAttributes) { throw null; }
public static void ValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { }
public static void ValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, bool validateAllProperties) { }
public static void ValidateProperty(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { }
public static void ValidateValue(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationAttribute> validationAttributes) { }
}
}
namespace System.ComponentModel.DataAnnotations.Schema
{
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class ColumnAttribute : System.Attribute
{
public ColumnAttribute() { }
public ColumnAttribute(string name) { }
public string Name { get { throw null; } }
public int Order { get { throw null; } set { } }
public string TypeName { get { throw null; } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple = false)]
public partial class ComplexTypeAttribute : System.Attribute
{
public ComplexTypeAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class DatabaseGeneratedAttribute : System.Attribute
{
public DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption databaseGeneratedOption) { }
public System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption DatabaseGeneratedOption { get { throw null; } }
}
public enum DatabaseGeneratedOption
{
Computed = 2,
Identity = 1,
None = 0,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class ForeignKeyAttribute : System.Attribute
{
public ForeignKeyAttribute(string name) { }
public string Name { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class InversePropertyAttribute : System.Attribute
{
public InversePropertyAttribute(string property) { }
public string Property { get { throw null; } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(388), AllowMultiple = false)]
public partial class NotMappedAttribute : System.Attribute
{
public NotMappedAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple = false)]
public partial class TableAttribute : System.Attribute
{
public TableAttribute(string name) { }
public string Name { get { throw null; } }
public string Schema { get { throw null; } set { } }
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Physics;
using System;
using UnityEngine;
using UnityEngine.Serialization;
namespace Microsoft.MixedReality.Toolkit.Utilities.Solvers
{
/// <summary>
/// SurfaceMagnetism casts rays to Surfaces in the world and aligns the object to the hit surface.
/// </summary>
[AddComponentMenu("Scripts/MRTK/SDK/SurfaceMagnetism")]
public class SurfaceMagnetism : Solver
{
#region Enums
/// <summary>
/// Raycast direction mode for solver
/// </summary>
public enum RaycastDirectionMode
{
/// <summary>
/// Cast from Tracked Target in facing direction
/// </summary>
TrackedTargetForward = 0,
/// <summary>
/// Cast from Tracked Target position to this object's position
/// </summary>
ToObject,
/// <summary>
/// Cast from Tracked Target Position to linked solver position
/// </summary>
ToLinkedPosition,
}
/// <summary>
/// Orientation mode for solver
/// </summary>
public enum OrientationMode
{
/// <summary>
/// No orienting
/// </summary>
None = 0,
/// <summary>
/// Face the tracked transform
/// </summary>
TrackedTarget = 1,
/// <summary>
/// Aligned to surface normal completely
/// </summary>
SurfaceNormal = 2,
/// <summary>
/// Blend between tracked transform and the surface normal orientation
/// </summary>
Blended = 3,
/// <summary>
/// Face toward this object's position
/// </summary>
TrackedOrigin = 4,
}
#endregion
#region SurfaceMagnetism Parameters
[SerializeField]
[Tooltip("Array of LayerMask to execute from highest to lowest priority. First layermask to provide a raycast hit will be used by component")]
private LayerMask[] magneticSurfaces = { UnityEngine.Physics.DefaultRaycastLayers };
/// <summary>
/// Array of LayerMask to execute from highest to lowest priority. First layermask to provide a raycast hit will be used by component
/// </summary>
public LayerMask[] MagneticSurfaces
{
get => magneticSurfaces;
set => magneticSurfaces = value;
}
[SerializeField]
[Tooltip("Max distance for raycast to check for surfaces")]
[FormerlySerializedAs("maxDistance")]
private float maxRaycastDistance = 50.0f;
/// <summary>
/// Max distance for raycast to check for surfaces
/// </summary>
public float MaxRaycastDistance
{
get => maxRaycastDistance;
set => maxRaycastDistance = value;
}
[SerializeField]
[Tooltip("Closest distance to bring object")]
[FormerlySerializedAs("closeDistance")]
private float closestDistance = 0.5f;
/// <summary>
/// Closest distance to bring object
/// </summary>
public float ClosestDistance
{
get => closestDistance;
set => closestDistance = value;
}
[SerializeField]
[Tooltip("Offset from surface along surface normal")]
private float surfaceNormalOffset = 0.5f;
/// <summary>
/// Offset from surface along surface normal
/// </summary>
public float SurfaceNormalOffset
{
get => surfaceNormalOffset;
set => surfaceNormalOffset = value;
}
[SerializeField]
[Tooltip("Offset from surface along ray cast direction")]
private float surfaceRayOffset = 0;
/// <summary>
/// Offset from surface along ray cast direction
/// </summary>
public float SurfaceRayOffset
{
get => surfaceRayOffset;
set => surfaceRayOffset = value;
}
[SerializeField]
[Tooltip("Surface raycast mode for solver")]
private SceneQueryType raycastMode = SceneQueryType.SimpleRaycast;
/// <summary>
/// Surface raycast mode for solver
/// </summary>
public SceneQueryType RaycastMode
{
get => raycastMode;
set => raycastMode = value;
}
#region Box Raycast Parameters
[SerializeField]
[Tooltip("Number of rays per edge, should be odd. Total casts is n^2")]
private int boxRaysPerEdge = 3;
/// <summary>
/// Number of rays per edge, should be odd. Total casts is n^2
/// </summary>
public int BoxRaysPerEdge
{
get => boxRaysPerEdge;
set => boxRaysPerEdge = value;
}
[SerializeField]
[Tooltip("If true, use orthographic casting for box lines instead of perspective")]
private bool orthographicBoxCast = false;
/// <summary>
/// If true, use orthographic casting for box lines instead of perspective
/// </summary>
public bool OrthographicBoxCast
{
get => orthographicBoxCast;
set => orthographicBoxCast = value;
}
[SerializeField]
[Tooltip("Align to ray cast direction if box cast hits many normals facing in varying directions")]
private float maximumNormalVariance = 0.5f;
/// <summary>
/// Align to ray cast direction if box cast hits many normals facing in varying directions
/// </summary>
public float MaximumNormalVariance
{
get => maximumNormalVariance;
set => maximumNormalVariance = value;
}
#endregion
#region Sphere Raycast Parameters
[SerializeField]
[Tooltip("Radius to use for sphere cast")]
private float sphereSize = 1.0f;
/// <summary>
/// Radius to use for sphere cast
/// </summary>
public float SphereSize
{
get => sphereSize;
set => sphereSize = value;
}
#endregion
[SerializeField]
[Tooltip("When doing volume casts, use size override if non-zero instead of object's current scale")]
private float volumeCastSizeOverride = 0;
/// <summary>
/// When doing volume casts, use size override if non-zero instead of object's current scale
/// </summary>
public float VolumeCastSizeOverride
{
get => volumeCastSizeOverride;
set => volumeCastSizeOverride = value;
}
[SerializeField]
[Tooltip("When doing volume casts, use linked AltScale instead of object's current scale")]
private bool useLinkedAltScaleOverride = false;
/// <summary>
/// When doing volume casts, use linked AltScale instead of object's current scale
/// </summary>
public bool UseLinkedAltScaleOverride
{
get => useLinkedAltScaleOverride;
set => useLinkedAltScaleOverride = value;
}
[SerializeField]
[Tooltip("Raycast direction type. Default is forward direction of Tracked Target transform")]
private RaycastDirectionMode currentRaycastDirectionMode = RaycastDirectionMode.TrackedTargetForward;
/// <summary>
/// Raycast direction type. Default is forward direction of Tracked Target transform
/// </summary>
public RaycastDirectionMode CurrentRaycastDirectionMode
{
get => currentRaycastDirectionMode;
set => currentRaycastDirectionMode = value;
}
[SerializeField]
[Tooltip("How solver will orient model. None = no orienting, TrackedTarget = Face tracked target transform, SurfaceNormal = Aligned to surface normal completely, Blended = blend between tracked transform and surface orientation")]
private OrientationMode orientationMode = OrientationMode.TrackedTarget;
/// <summary>
/// How solver will orient model. See OrientationMode enum for possible modes. When mode=Blended, use OrientationBlend property to define ratio for blending
/// </summary>
public OrientationMode CurrentOrientationMode
{
get => orientationMode;
set => orientationMode = value;
}
[SerializeField]
[Tooltip("Value used for when OrientationMode=Blended. If 0.0 orientation is driven as if in TrackedTarget mode, and if 1.0 orientation is driven as if in SurfaceNormal mode")]
private float orientationBlend = 0.65f;
/// <summary>
/// Value used for when Orientation Mode=Blended. If 0.0 orientation is driven all by TrackedTarget mode and if 1.0 orientation is driven all by SurfaceNormal mode
/// </summary>
public float OrientationBlend
{
get => orientationBlend;
set => orientationBlend = value;
}
[SerializeField]
[Tooltip("If true, ensures object is kept vertical for TrackedTarget, SurfaceNormal, and Blended Orientation Modes")]
private bool keepOrientationVertical = true;
/// <summary>
/// If true, ensures object is kept vertical for TrackedTarget, SurfaceNormal, and Blended Orientation Modes
/// </summary>
public bool KeepOrientationVertical
{
get => keepOrientationVertical;
set => keepOrientationVertical = value;
}
[SerializeField]
[Tooltip("If enabled, the debug lines will be drawn in the editor")]
private bool debugEnabled = false;
/// <summary>
/// If enabled, the debug lines will be drawn in the editor
/// </summary>
public bool DebugEnabled
{
get => debugEnabled;
set => debugEnabled = value;
}
#endregion
/// <summary>
/// Whether or not the object is currently magnetized to a surface.
/// </summary>
public bool OnSurface { get; private set; }
private const float MaxDot = 0.97f;
private RayStep currentRayStep = new RayStep();
private BoxCollider boxCollider;
private Vector3 RaycastOrigin => SolverHandler.TransformTarget == null ? Vector3.zero : SolverHandler.TransformTarget.position;
/// <summary>
/// Which point should the ray cast toward? Not really the 'end' of the ray. The ray may be cast along
/// the head facing direction, from the eye to the object, or to the solver's linked position (working from
/// the previous solvers)
/// </summary>
private Vector3 RaycastEndPoint
{
get
{
Vector3 origin = RaycastOrigin;
Vector3 endPoint = Vector3.forward;
switch (CurrentRaycastDirectionMode)
{
case RaycastDirectionMode.TrackedTargetForward:
if (SolverHandler != null && SolverHandler.TransformTarget != null)
{
endPoint = SolverHandler.TransformTarget.position + SolverHandler.TransformTarget.forward;
}
break;
case RaycastDirectionMode.ToObject:
endPoint = transform.position;
break;
case RaycastDirectionMode.ToLinkedPosition:
endPoint = SolverHandler.GoalPosition;
break;
}
return endPoint;
}
}
/// <summary>
/// Calculate the raycast direction based on the two ray points
/// </summary>
private Vector3 RaycastDirection
{
get
{
Vector3 direction = Vector3.forward;
if (CurrentRaycastDirectionMode == RaycastDirectionMode.TrackedTargetForward)
{
if (SolverHandler.TransformTarget != null)
{
direction = SolverHandler.TransformTarget.forward;
}
}
else
{
direction = (RaycastEndPoint - RaycastOrigin).normalized;
}
return direction;
}
}
/// <summary>
/// A constant scale override may be specified for volumetric raycasts, otherwise uses the current value of the solver link's alt scale
/// </summary>
private float ScaleOverride => useLinkedAltScaleOverride ? SolverHandler.AltScale.Current.magnitude : volumeCastSizeOverride;
/// <summary>
/// Calculates how the object should orient to the surface.
/// </summary>
/// <param name="direction">direction of tracked target</param>
/// <param name="surfaceNormal">normal of surface at hit point</param>
/// <returns>Quaternion, the orientation to use for the object</returns>
private Quaternion CalculateMagnetismOrientation(Vector3 direction, Vector3 surfaceNormal)
{
if (KeepOrientationVertical)
{
direction.y = 0;
surfaceNormal.y = 0;
}
var trackedReferenceRotation = Quaternion.LookRotation(-direction, Vector3.up);
var surfaceReferenceRotation = Quaternion.LookRotation(-surfaceNormal, Vector3.up);
switch (CurrentOrientationMode)
{
case OrientationMode.None:
return SolverHandler.GoalRotation;
case OrientationMode.TrackedTarget:
return trackedReferenceRotation;
case OrientationMode.SurfaceNormal:
return surfaceReferenceRotation;
case OrientationMode.Blended:
return Quaternion.Slerp(trackedReferenceRotation, surfaceReferenceRotation, orientationBlend);
case OrientationMode.TrackedOrigin:
return Quaternion.LookRotation(direction, Vector3.up);
default:
return Quaternion.identity;
}
}
/// <inheritdoc />
public override void SolverUpdate()
{
// Pass-through by default
GoalPosition = WorkingPosition;
GoalRotation = WorkingRotation;
// Determine raycast params. Update struct to skip instantiation
Vector3 origin = RaycastOrigin;
Vector3 endpoint = RaycastEndPoint;
currentRayStep.UpdateRayStep(ref origin, ref endpoint);
// Skip if there isn't a valid direction
if (currentRayStep.Direction == Vector3.zero)
{
return;
}
if (DebugEnabled)
{
Debug.DrawLine(currentRayStep.Origin, currentRayStep.Terminus, Color.magenta);
}
switch (RaycastMode)
{
case SceneQueryType.SimpleRaycast:
SimpleRaycastStepUpdate(ref this.currentRayStep);
break;
case SceneQueryType.BoxRaycast:
BoxRaycastStepUpdate(ref this.currentRayStep);
break;
case SceneQueryType.SphereCast:
SphereRaycastStepUpdate(ref this.currentRayStep);
break;
case SceneQueryType.SphereOverlap:
Debug.LogError("Raycast mode set to SphereOverlap which is not valid for SurfaceMagnetism component. Disabling update solvers...");
SolverHandler.UpdateSolvers = false;
break;
}
}
/// <summary>
/// Calculate solver for simple raycast with provided ray
/// </summary>
/// <param name="rayStep">start/end ray passed by read-only reference to avoid struct-copy performance</param>
private void SimpleRaycastStepUpdate(ref RayStep rayStep)
{
bool isHit;
RaycastHit result;
// Do the cast!
isHit = MixedRealityRaycaster.RaycastSimplePhysicsStep(rayStep, maxRaycastDistance, magneticSurfaces, false, out result);
OnSurface = isHit;
// Enforce CloseDistance
Vector3 hitDelta = result.point - rayStep.Origin;
float length = hitDelta.magnitude;
if (length < closestDistance)
{
result.point = rayStep.Origin + rayStep.Direction * closestDistance;
}
// Apply results
if (isHit)
{
GoalPosition = result.point + surfaceNormalOffset * result.normal + surfaceRayOffset * rayStep.Direction;
GoalRotation = CalculateMagnetismOrientation(rayStep.Direction, result.normal);
}
}
/// <summary>
/// Calculate solver for sphere raycast with provided ray
/// </summary>
/// <param name="rayStep">start/end ray passed by read-only reference to avoid struct-copy performance</param>
private void SphereRaycastStepUpdate(ref RayStep rayStep)
{
bool isHit;
RaycastHit result;
// Do the cast!
float size = ScaleOverride > 0 ? ScaleOverride : transform.lossyScale.x * sphereSize;
isHit = MixedRealityRaycaster.RaycastSpherePhysicsStep(rayStep, size, maxRaycastDistance, magneticSurfaces, false, out result);
OnSurface = isHit;
// Enforce CloseDistance
Vector3 hitDelta = result.point - rayStep.Origin;
float length = hitDelta.magnitude;
if (length < closestDistance)
{
result.point = rayStep.Origin + rayStep.Direction * closestDistance;
}
// Apply results
if (isHit)
{
GoalPosition = result.point + surfaceNormalOffset * result.normal + surfaceRayOffset * rayStep.Direction;
GoalRotation = CalculateMagnetismOrientation(rayStep.Direction, result.normal);
}
}
/// <summary>
/// Calculate solver for box raycast with provided ray
/// </summary>
/// <param name="rayStep">start/end ray passed by read-only reference to avoid struct-copy performance</param>
private void BoxRaycastStepUpdate(ref RayStep rayStep)
{
Vector3 scale = ScaleOverride > 0 ? transform.lossyScale.normalized * ScaleOverride : transform.lossyScale;
Quaternion orientation = orientationMode == OrientationMode.None ?
Quaternion.LookRotation(rayStep.Direction, Vector3.up) :
CalculateMagnetismOrientation(rayStep.Direction, Vector3.up);
Matrix4x4 targetMatrix = Matrix4x4.TRS(Vector3.zero, orientation, scale);
if (this.boxCollider == null)
{
this.boxCollider = GetComponent<BoxCollider>();
}
Debug.Assert(boxCollider != null, $"Missing a box collider for Surface Magnetism on {gameObject}");
Vector3 extents = boxCollider.size;
Vector3[] positions;
Vector3[] normals;
bool[] hits;
if (MixedRealityRaycaster.RaycastBoxPhysicsStep(rayStep, extents, transform.position, targetMatrix, maxRaycastDistance, magneticSurfaces, boxRaysPerEdge, orthographicBoxCast, false, out positions, out normals, out hits))
{
Plane plane;
float distance;
// Place an unconstrained plane down the ray. Don't use vertical constrain.
FindPlacementPlane(rayStep.Origin, rayStep.Direction, positions, normals, hits, boxCollider.size.x, maximumNormalVariance, false, orientationMode == OrientationMode.None, out plane, out distance);
// If placing on a horizontal surface, need to adjust the calculated distance by half the app height
float verticalCorrectionOffset = 0;
if (IsNormalVertical(plane.normal) && !Mathf.Approximately(rayStep.Direction.y, 0))
{
float boxSurfaceVerticalOffset = targetMatrix.MultiplyVector(new Vector3(0, extents.y * 0.5f, 0)).magnitude;
Vector3 correctionVector = boxSurfaceVerticalOffset * (rayStep.Direction / rayStep.Direction.y);
verticalCorrectionOffset = -correctionVector.magnitude;
}
float boxSurfaceOffset = targetMatrix.MultiplyVector(new Vector3(0, 0, extents.z * 0.5f)).magnitude;
// Apply boxSurfaceOffset to ray direction and not surface normal direction to reduce sliding
GoalPosition = rayStep.Origin + rayStep.Direction * Mathf.Max(closestDistance, distance + surfaceRayOffset + boxSurfaceOffset + verticalCorrectionOffset) + plane.normal * (0 * boxSurfaceOffset + surfaceNormalOffset);
GoalRotation = CalculateMagnetismOrientation(rayStep.Direction, plane.normal);
OnSurface = true;
}
else
{
OnSurface = false;
}
}
/// <summary>
/// Calculates a plane from all raycast hit locations upon which the object may align. Used in Box Raycast Mode.
/// </summary>
private void FindPlacementPlane(Vector3 origin, Vector3 direction, Vector3[] positions, Vector3[] normals, bool[] hits, float assetWidth, float maxNormalVariance, bool constrainVertical, bool useClosestDistance, out Plane plane, out float closestDistance)
{
int rayCount = positions.Length;
Vector3 originalDirection = direction;
if (constrainVertical)
{
direction.y = 0.0f;
direction = direction.normalized;
}
// Go through all the points and find the closest distance
closestDistance = float.PositiveInfinity;
int numHits = 0;
int closestPointIdx = -1;
float farthestDistance = 0f;
var averageNormal = Vector3.zero;
for (int hitIndex = 0; hitIndex < rayCount; hitIndex++)
{
if (hits[hitIndex])
{
float distance = Vector3.Dot(direction, positions[hitIndex] - origin);
if (distance < closestDistance)
{
closestPointIdx = hitIndex;
closestDistance = distance;
}
if (distance > farthestDistance)
{
farthestDistance = distance;
}
averageNormal += normals[hitIndex];
++numHits;
}
}
Vector3 closestPoint = positions[closestPointIdx];
averageNormal /= numHits;
// Calculate variance of all normals
float variance = 0;
for (int hitIndex = 0; hitIndex < rayCount; ++hitIndex)
{
if (hits[hitIndex])
{
variance += (normals[hitIndex] - averageNormal).magnitude;
}
}
variance /= numHits;
// If variance is too high, I really don't want to deal with this surface
// And if we don't even have enough rays, I'm not confident about this at all
if (variance > maxNormalVariance || numHits < rayCount * 0.25f)
{
plane = new Plane(-direction, closestPoint);
return;
}
// go through all the points and find the most orthogonal plane
var lowAngle = float.PositiveInfinity;
var highAngle = float.NegativeInfinity;
int lowIndex = -1;
int highIndex = -1;
for (int hitIndex = 0; hitIndex < rayCount; hitIndex++)
{
if (hits[hitIndex] == false || hitIndex == closestPointIdx)
{
continue;
}
Vector3 difference = positions[hitIndex] - closestPoint;
if (constrainVertical)
{
difference.y = 0.0f;
difference.Normalize();
if (difference == Vector3.zero)
{
continue;
}
}
difference.Normalize();
float angle = Vector3.Dot(direction, difference);
if (angle < lowAngle)
{
lowAngle = angle;
lowIndex = hitIndex;
}
}
if (!constrainVertical && lowIndex != -1)
{
for (int hitIndex = 0; hitIndex < rayCount; hitIndex++)
{
if (hits[hitIndex] == false || hitIndex == closestPointIdx || hitIndex == lowIndex)
{
continue;
}
float dot = Mathf.Abs(Vector3.Dot((positions[hitIndex] - closestPoint).normalized, (positions[lowIndex] - closestPoint).normalized));
if (dot > MaxDot)
{
continue;
}
float nextAngle = Mathf.Abs(Vector3.Dot(direction, Vector3.Cross(positions[lowIndex] - closestPoint, positions[hitIndex] - closestPoint).normalized));
if (nextAngle > highAngle)
{
highAngle = nextAngle;
highIndex = hitIndex;
}
}
}
Vector3 placementNormal;
if (lowIndex != -1)
{
if (debugEnabled)
{
Debug.DrawLine(closestPoint, positions[lowIndex], Color.red);
}
if (highIndex != -1)
{
if (debugEnabled)
{
Debug.DrawLine(closestPoint, positions[highIndex], Color.green);
}
placementNormal = Vector3.Cross(positions[lowIndex] - closestPoint, positions[highIndex] - closestPoint).normalized;
}
else
{
Vector3 planeUp = Vector3.Cross(positions[lowIndex] - closestPoint, direction);
placementNormal = Vector3.Cross(positions[lowIndex] - closestPoint, constrainVertical ? Vector3.up : planeUp).normalized;
}
if (debugEnabled)
{
Debug.DrawLine(closestPoint, closestPoint + placementNormal, Color.blue);
}
}
else
{
placementNormal = direction * -1.0f;
}
if (Vector3.Dot(placementNormal, direction) > 0.0f)
{
placementNormal *= -1.0f;
}
plane = new Plane(placementNormal, closestPoint);
if (debugEnabled)
{
Debug.DrawRay(closestPoint, placementNormal, Color.cyan);
}
// Figure out how far the plane should be.
if (!useClosestDistance && closestPointIdx >= 0)
{
float centerPlaneDistance;
if (plane.Raycast(new Ray(origin, originalDirection), out centerPlaneDistance) || !centerPlaneDistance.Equals(0.0f))
{
// When the plane is nearly parallel to the user, we need to clamp the distance to where the raycasts hit.
closestDistance = Mathf.Clamp(centerPlaneDistance, closestDistance, farthestDistance + assetWidth * 0.5f);
}
else
{
Debug.LogError("FindPlacementPlane: Not expected to have the center point not intersect the plane.");
}
}
}
/// <summary>
/// Checks if a normal is nearly vertical
/// </summary>
/// <returns>Returns true, if normal is vertical.</returns>
private static bool IsNormalVertical(Vector3 normal) => 1f - Mathf.Abs(normal.y) < 0.01f;
#region Obsolete
/// <summary>
/// Max distance for raycast to check for surfaces
/// </summary>
[Obsolete("Use MaxRaycastDistance instead")]
public float MaxDistance
{
get => maxRaycastDistance;
set => maxRaycastDistance = value;
}
/// <summary>
/// Closest distance to bring object
/// </summary>
[Obsolete("Use ClosestDistance instead")]
public float CloseDistance
{
get { return closestDistance; }
set { closestDistance = value; }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 AlignRightSByte27()
{
var test = new ImmBinaryOpTest__AlignRightSByte27();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.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 (Avx.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 class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ImmBinaryOpTest__AlignRightSByte27
{
private struct TestStruct
{
public Vector256<SByte> _fld1;
public Vector256<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__AlignRightSByte27 testClass)
{
var result = Avx2.AlignRight(_fld1, _fld2, 27);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector256<SByte> _clsVar1;
private static Vector256<SByte> _clsVar2;
private Vector256<SByte> _fld1;
private Vector256<SByte> _fld2;
private SimpleBinaryOpTest__DataTable<SByte, SByte, SByte> _dataTable;
static ImmBinaryOpTest__AlignRightSByte27()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
}
public ImmBinaryOpTest__AlignRightSByte27()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new SimpleBinaryOpTest__DataTable<SByte, SByte, SByte>(_data1, _data2, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.AlignRight(
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr),
27
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.AlignRight(
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)),
27
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.AlignRight(
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)),
27
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr),
(byte)27
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)),
(byte)27
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AlignRight), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)),
(byte)27
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.AlignRight(
_clsVar1,
_clsVar2,
27
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr);
var result = Avx2.AlignRight(left, right, 27);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr));
var result = Avx2.AlignRight(left, right, 27);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr));
var result = Avx2.AlignRight(left, right, 27);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__AlignRightSByte27();
var result = Avx2.AlignRight(test._fld1, test._fld2, 27);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.AlignRight(_fld1, _fld2, 27);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.AlignRight(test._fld1, test._fld2, 27);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<SByte> left, Vector256<SByte> right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != left[11])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((result[i] != ((i < 16) ? ((i < 5) ? left[i + 11] : 0) : ((i < 21) ? left[i + 11] : 0))))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.AlignRight)}<SByte>(Vector256<SByte>.27, Vector256<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
#if !netstandard
using Internal.Runtime.CompilerServices;
#endif
namespace System.Runtime.CompilerServices
{
/// <summary>Provides an awaitable type that enables configured awaits on a <see cref="ValueTask"/>.</summary>
[StructLayout(LayoutKind.Auto)]
public readonly struct ConfiguredValueTaskAwaitable
{
/// <summary>The wrapped <see cref="Task"/>.</summary>
private readonly ValueTask _value;
/// <summary>Initializes the awaitable.</summary>
/// <param name="value">The wrapped <see cref="ValueTask"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ConfiguredValueTaskAwaitable(in ValueTask value) => _value = value;
/// <summary>Returns an awaiter for this <see cref="ConfiguredValueTaskAwaitable"/> instance.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ConfiguredValueTaskAwaiter GetAwaiter() => new ConfiguredValueTaskAwaiter(in _value);
/// <summary>Provides an awaiter for a <see cref="ConfiguredValueTaskAwaitable"/>.</summary>
[StructLayout(LayoutKind.Auto)]
public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, IStateMachineBoxAwareAwaiter
{
/// <summary>The value being awaited.</summary>
private readonly ValueTask _value;
/// <summary>Initializes the awaiter.</summary>
/// <param name="value">The value to be awaited.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ConfiguredValueTaskAwaiter(in ValueTask value) => _value = value;
/// <summary>Gets whether the <see cref="ConfiguredValueTaskAwaitable"/> has completed.</summary>
public bool IsCompleted
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _value.IsCompleted;
}
/// <summary>Gets the result of the ValueTask.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GetResult() => _value.ThrowIfCompletedUnsuccessfully();
/// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable"/>.</summary>
public void OnCompleted(Action continuation)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource);
if (obj is Task t)
{
t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token,
ValueTaskSourceOnCompletedFlags.FlowExecutionContext |
(_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None));
}
else
{
ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
}
}
/// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable"/>.</summary>
public void UnsafeOnCompleted(Action continuation)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource);
if (obj is Task t)
{
t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token,
_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
}
else
{
ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
}
}
void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource);
if (obj is Task t)
{
TaskAwaiter.UnsafeOnCompletedInternal(t, box, _value._continueOnCapturedContext);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource>(obj).OnCompleted(ThreadPoolGlobals.s_invokeAsyncStateMachineBox, box, _value._token,
_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
}
else
{
TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext);
}
}
}
}
/// <summary>Provides an awaitable type that enables configured awaits on a <see cref="ValueTask{TResult}"/>.</summary>
/// <typeparam name="TResult">The type of the result produced.</typeparam>
[StructLayout(LayoutKind.Auto)]
public readonly struct ConfiguredValueTaskAwaitable<TResult>
{
/// <summary>The wrapped <see cref="ValueTask{TResult}"/>.</summary>
private readonly ValueTask<TResult> _value;
/// <summary>Initializes the awaitable.</summary>
/// <param name="value">The wrapped <see cref="ValueTask{TResult}"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ConfiguredValueTaskAwaitable(in ValueTask<TResult> value) => _value = value;
/// <summary>Returns an awaiter for this <see cref="ConfiguredValueTaskAwaitable{TResult}"/> instance.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ConfiguredValueTaskAwaiter GetAwaiter() => new ConfiguredValueTaskAwaiter(in _value);
/// <summary>Provides an awaiter for a <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
[StructLayout(LayoutKind.Auto)]
public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, IStateMachineBoxAwareAwaiter
{
/// <summary>The value being awaited.</summary>
private readonly ValueTask<TResult> _value;
/// <summary>Initializes the awaiter.</summary>
/// <param name="value">The value to be awaited.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ConfiguredValueTaskAwaiter(in ValueTask<TResult> value) => _value = value;
/// <summary>Gets whether the <see cref="ConfiguredValueTaskAwaitable{TResult}"/> has completed.</summary>
public bool IsCompleted
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _value.IsCompleted;
}
/// <summary>Gets the result of the ValueTask.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TResult GetResult() => _value.Result;
/// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
public void OnCompleted(Action continuation)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>);
if (obj is Task<TResult> t)
{
t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token,
ValueTaskSourceOnCompletedFlags.FlowExecutionContext |
(_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None));
}
else
{
ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
}
}
/// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
public void UnsafeOnCompleted(Action continuation)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>);
if (obj is Task<TResult> t)
{
t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token,
_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
}
else
{
ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
}
}
void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box)
{
object? obj = _value._obj;
Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>);
if (obj is Task<TResult> t)
{
TaskAwaiter.UnsafeOnCompletedInternal(t, box, _value._continueOnCapturedContext);
}
else if (obj != null)
{
Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ThreadPoolGlobals.s_invokeAsyncStateMachineBox, box, _value._token,
_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
}
else
{
TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext);
}
}
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
namespace CSR.Parser {
public class Token {
public int kind; // token kind
public int pos; // token position in the source text (starting at 0)
public int col; // token column (starting at 1)
public int line; // token line (starting at 1)
public string val; // token value
public Token next; // ML 2005-03-11 Tokens are kept in linked list
}
//-----------------------------------------------------------------------------------
// Buffer
//-----------------------------------------------------------------------------------
public class Buffer {
// This Buffer supports the following cases:
// 1) seekable stream (file)
// a) whole stream in buffer
// b) part of stream in buffer
// 2) non seekable stream (network, console)
public const int EOF = char.MaxValue + 1;
const int MIN_BUFFER_LENGTH = 1024; // 1KB
const int MAX_BUFFER_LENGTH = MIN_BUFFER_LENGTH * 64; // 64KB
byte[] buf; // input buffer
int bufStart; // position of first byte in buffer relative to input stream
int bufLen; // length of buffer
int fileLen; // length of input stream (may change if the stream is no file)
int bufPos; // current position in buffer
Stream stream; // input stream (seekable)
bool isUserStream; // was the stream opened by the user?
public Buffer (Stream s, bool isUserStream) {
stream = s; this.isUserStream = isUserStream;
if (stream.CanSeek) {
fileLen = (int) stream.Length;
bufLen = Math.Min(fileLen, MAX_BUFFER_LENGTH);
bufStart = Int32.MaxValue; // nothing in the buffer so far
} else {
fileLen = bufLen = bufStart = 0;
}
buf = new byte[(bufLen>0) ? bufLen : MIN_BUFFER_LENGTH];
if (fileLen > 0) Pos = 0; // setup buffer to position 0 (start)
else bufPos = 0; // index 0 is already after the file, thus Pos = 0 is invalid
if (bufLen == fileLen && stream.CanSeek) Close();
}
protected Buffer(Buffer b) { // called in UTF8Buffer constructor
buf = b.buf;
bufStart = b.bufStart;
bufLen = b.bufLen;
fileLen = b.fileLen;
bufPos = b.bufPos;
stream = b.stream;
// keep destructor from closing the stream
b.stream = null;
isUserStream = b.isUserStream;
}
~Buffer() { Close(); }
protected void Close() {
if (!isUserStream && stream != null) {
stream.Close();
stream = null;
}
}
public virtual int Read () {
if (bufPos < bufLen) {
return buf[bufPos++];
} else if (Pos < fileLen) {
Pos = Pos; // shift buffer start to Pos
return buf[bufPos++];
} else if (stream != null && !stream.CanSeek && ReadNextStreamChunk() > 0) {
return buf[bufPos++];
} else {
return EOF;
}
}
public int Peek () {
int curPos = Pos;
int ch = Read();
Pos = curPos;
return ch;
}
public string GetString (int beg, int end) {
int len = end - beg;
char[] buf = new char[len];
int oldPos = Pos;
Pos = beg;
for (int i = 0; i < len; i++) buf[i] = (char) Read();
Pos = oldPos;
return new String(buf);
}
public int Pos {
get { return bufPos + bufStart; }
set {
if (value >= fileLen && stream != null && !stream.CanSeek) {
// Wanted position is after buffer and the stream
// is not seek-able e.g. network or console,
// thus we have to read the stream manually till
// the wanted position is in sight.
while (value >= fileLen && ReadNextStreamChunk() > 0);
}
if (value < 0 || value > fileLen) {
throw new FatalError("buffer out of bounds access, position: " + value);
}
if (value >= bufStart && value < bufStart + bufLen) { // already in buffer
bufPos = value - bufStart;
} else if (stream != null) { // must be swapped in
stream.Seek(value, SeekOrigin.Begin);
bufLen = stream.Read(buf, 0, buf.Length);
bufStart = value; bufPos = 0;
} else {
// set the position to the end of the file, Pos will return fileLen.
bufPos = fileLen - bufStart;
}
}
}
// Read the next chunk of bytes from the stream, increases the buffer
// if needed and updates the fields fileLen and bufLen.
// Returns the number of bytes read.
private int ReadNextStreamChunk() {
int free = buf.Length - bufLen;
if (free == 0) {
// in the case of a growing input stream
// we can neither seek in the stream, nor can we
// foresee the maximum length, thus we must adapt
// the buffer size on demand.
byte[] newBuf = new byte[bufLen * 2];
Array.Copy(buf, newBuf, bufLen);
buf = newBuf;
free = bufLen;
}
int read = stream.Read(buf, bufLen, free);
if (read > 0) {
fileLen = bufLen = (bufLen + read);
return read;
}
// end of stream reached
return 0;
}
}
//-----------------------------------------------------------------------------------
// UTF8Buffer
//-----------------------------------------------------------------------------------
public class UTF8Buffer: Buffer {
public UTF8Buffer(Buffer b): base(b) {}
public override int Read() {
int ch;
do {
ch = base.Read();
// until we find a uft8 start (0xxxxxxx or 11xxxxxx)
} while ((ch >= 128) && ((ch & 0xC0) != 0xC0) && (ch != EOF));
if (ch < 128 || ch == EOF) {
// nothing to do, first 127 chars are the same in ascii and utf8
// 0xxxxxxx or end of file character
} else if ((ch & 0xF0) == 0xF0) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x07; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F; ch = base.Read();
int c4 = ch & 0x3F;
ch = (((((c1 << 6) | c2) << 6) | c3) << 6) | c4;
} else if ((ch & 0xE0) == 0xE0) {
// 1110xxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x0F; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F;
ch = (((c1 << 6) | c2) << 6) | c3;
} else if ((ch & 0xC0) == 0xC0) {
// 110xxxxx 10xxxxxx
int c1 = ch & 0x1F; ch = base.Read();
int c2 = ch & 0x3F;
ch = (c1 << 6) | c2;
}
return ch;
}
}
//-----------------------------------------------------------------------------------
// Scanner
//-----------------------------------------------------------------------------------
public class Scanner {
const char EOL = '\n';
const int eofSym = 0; /* pdt */
const int maxT = 52;
const int noSym = 52;
public Buffer buffer; // scanner buffer
Token t; // current token
int ch; // current input character
int pos; // byte position of current character
int col; // column number of current character
int line; // line number of current character
int oldEols; // EOLs that appeared in a comment;
Dictionary<int, int> start; // maps first token character to start state
Token tokens; // list of tokens already peeked (first token is a dummy)
Token pt; // current peek token
char[] tval = new char[128]; // text of current token
int tlen; // length of current token
public Scanner (string fileName) {
try {
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
buffer = new Buffer(stream, false);
Init();
} catch (IOException) {
throw new FatalError("Cannot open file " + fileName);
}
}
public Scanner (Stream s) {
buffer = new Buffer(s, true);
Init();
}
void Init() {
pos = -1; line = 1; col = 0;
oldEols = 0;
NextCh();
if (ch == 0xEF) { // check optional byte order mark for UTF-8
NextCh(); int ch1 = ch;
NextCh(); int ch2 = ch;
if (ch1 != 0xBB || ch2 != 0xBF) {
throw new FatalError(String.Format("illegal byte order mark: EF {0,2:X} {1,2:X}", ch1, ch2));
}
buffer = new UTF8Buffer(buffer); col = 0;
NextCh();
}
start = new Dictionary<int, int>(128);
for (int i = 65; i <= 90; ++i) start[i] = 1;
for (int i = 95; i <= 95; ++i) start[i] = 1;
for (int i = 97; i <= 122; ++i) start[i] = 1;
for (int i = 170; i <= 170; ++i) start[i] = 1;
for (int i = 181; i <= 181; ++i) start[i] = 1;
for (int i = 186; i <= 186; ++i) start[i] = 1;
for (int i = 192; i <= 214; ++i) start[i] = 1;
for (int i = 216; i <= 246; ++i) start[i] = 1;
for (int i = 248; i <= 255; ++i) start[i] = 1;
for (int i = 49; i <= 57; ++i) start[i] = 59;
start[92] = 15;
start[48] = 60;
start[46] = 61;
start[34] = 43;
start[61] = 62;
start[58] = 45;
start[44] = 46;
start[62] = 63;
start[123] = 49;
start[91] = 50;
start[40] = 51;
start[60] = 70;
start[45] = 52;
start[33] = 71;
start[43] = 53;
start[125] = 54;
start[93] = 55;
start[41] = 56;
start[59] = 57;
start[42] = 58;
start[47] = 68;
start[37] = 69;
start[Buffer.EOF] = -1;
pt = tokens = new Token(); // first token is a dummy
}
void NextCh() {
if (oldEols > 0) { ch = EOL; oldEols--; }
else {
pos = buffer.Pos;
ch = buffer.Read(); col++;
// replace isolated '\r' by '\n' in order to make
// eol handling uniform across Windows, Unix and Mac
if (ch == '\r' && buffer.Peek() != '\n') ch = EOL;
if (ch == EOL) { line++; col = 0; }
}
}
void AddCh() {
if (tlen >= tval.Length) {
char[] newBuf = new char[2 * tval.Length];
Array.Copy(tval, 0, newBuf, 0, tval.Length);
tval = newBuf;
}
tval[tlen++] = (char)ch;
NextCh();
}
bool Comment0() {
int level = 1, pos0 = pos, line0 = line, col0 = col;
NextCh();
if (ch == '/') {
NextCh();
for(;;) {
if (ch == 10) {
level--;
if (level == 0) { oldEols = line - line0; NextCh(); return true; }
NextCh();
} else if (ch == Buffer.EOF) return false;
else NextCh();
}
} else {
buffer.Pos = pos0; NextCh(); line = line0; col = col0;
}
return false;
}
bool Comment1() {
int level = 1, pos0 = pos, line0 = line, col0 = col;
NextCh();
if (ch == '*') {
NextCh();
for(;;) {
if (ch == '*') {
NextCh();
if (ch == '/') {
level--;
if (level == 0) { oldEols = line - line0; NextCh(); return true; }
NextCh();
}
} else if (ch == Buffer.EOF) return false;
else NextCh();
}
} else {
buffer.Pos = pos0; NextCh(); line = line0; col = col0;
}
return false;
}
void CheckLiteral() {
switch (t.val) {
case "program": t.kind = 5; break;
case "function": t.kind = 6; break;
case "begin": t.kind = 7; break;
case "end": t.kind = 8; break;
case "for": t.kind = 9; break;
case "to": t.kind = 10; break;
case "downto": t.kind = 11; break;
case "do": t.kind = 12; break;
case "while": t.kind = 13; break;
case "var": t.kind = 14; break;
case "if": t.kind = 15; break;
case "else": t.kind = 16; break;
case "and": t.kind = 17; break;
case "or": t.kind = 18; break;
case "xor": t.kind = 19; break;
case "bool": t.kind = 20; break;
case "int": t.kind = 21; break;
case "double": t.kind = 22; break;
case "string": t.kind = 23; break;
case "void": t.kind = 24; break;
case "null": t.kind = 25; break;
case "false": t.kind = 26; break;
case "true": t.kind = 27; break;
case "return": t.kind = 28; break;
default: break;
}
}
Token NextToken() {
while (ch == ' ' ||
ch >= 9 && ch <= 10 || ch == 13
) NextCh();
if (ch == '/' && Comment0() ||ch == '/' && Comment1()) return NextToken();
int apx = 0;
t = new Token();
t.pos = pos; t.col = col; t.line = line;
int state;
try { state = start[ch]; } catch (KeyNotFoundException) { state = 0; }
tlen = 0; AddCh();
switch (state) {
case -1: { t.kind = eofSym; break; } // NextCh already done
case 0: { t.kind = noSym; break; } // NextCh already done
case 1:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'Z' || ch == '_' || ch >= 'a' && ch <= 'z' || ch == 160 || ch == 170 || ch == 181 || ch == 186 || ch >= 192 && ch <= 214 || ch >= 216 && ch <= 246 || ch >= 248 && ch <= 255) {AddCh(); goto case 1;}
else if (ch == 92) {AddCh(); goto case 2;}
else {t.kind = 1; t.val = new String(tval, 0, tlen); CheckLiteral(); return t;}
case 2:
if (ch == 'u') {AddCh(); goto case 3;}
else if (ch == 'U') {AddCh(); goto case 7;}
else {t.kind = noSym; break;}
case 3:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 4;}
else {t.kind = noSym; break;}
case 4:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 5;}
else {t.kind = noSym; break;}
case 5:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 6;}
else {t.kind = noSym; break;}
case 6:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 1;}
else {t.kind = noSym; break;}
case 7:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 8;}
else {t.kind = noSym; break;}
case 8:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 9;}
else {t.kind = noSym; break;}
case 9:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 10;}
else {t.kind = noSym; break;}
case 10:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 11;}
else {t.kind = noSym; break;}
case 11:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 12;}
else {t.kind = noSym; break;}
case 12:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 13;}
else {t.kind = noSym; break;}
case 13:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 14;}
else {t.kind = noSym; break;}
case 14:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 1;}
else {t.kind = noSym; break;}
case 15:
if (ch == 'u') {AddCh(); goto case 16;}
else if (ch == 'U') {AddCh(); goto case 20;}
else {t.kind = noSym; break;}
case 16:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 17;}
else {t.kind = noSym; break;}
case 17:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 18;}
else {t.kind = noSym; break;}
case 18:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 19;}
else {t.kind = noSym; break;}
case 19:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 1;}
else {t.kind = noSym; break;}
case 20:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 21;}
else {t.kind = noSym; break;}
case 21:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 22;}
else {t.kind = noSym; break;}
case 22:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 23;}
else {t.kind = noSym; break;}
case 23:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 24;}
else {t.kind = noSym; break;}
case 24:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 25;}
else {t.kind = noSym; break;}
case 25:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 26;}
else {t.kind = noSym; break;}
case 26:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 27;}
else {t.kind = noSym; break;}
case 27:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 1;}
else {t.kind = noSym; break;}
case 28:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 29;}
else {t.kind = noSym; break;}
case 29:
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') {AddCh(); goto case 29;}
else {t.kind = 2; break;}
case 30:
{
tlen -= apx;
buffer.Pos = t.pos; NextCh(); line = t.line; col = t.col;
for (int i = 0; i < tlen; i++) NextCh();
t.kind = 2; break;}
case 31:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 31;}
else if (ch == 'E' || ch == 'e') {AddCh(); goto case 32;}
else {t.kind = 3; break;}
case 32:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 34;}
else if (ch == '+' || ch == '-') {AddCh(); goto case 33;}
else {t.kind = noSym; break;}
case 33:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 34;}
else {t.kind = noSym; break;}
case 34:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 34;}
else {t.kind = 3; break;}
case 35:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 35;}
else if (ch == 'E' || ch == 'e') {AddCh(); goto case 36;}
else {t.kind = 3; break;}
case 36:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 38;}
else if (ch == '+' || ch == '-') {AddCh(); goto case 37;}
else {t.kind = noSym; break;}
case 37:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 38;}
else {t.kind = noSym; break;}
case 38:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 38;}
else {t.kind = 3; break;}
case 39:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 41;}
else if (ch == '+' || ch == '-') {AddCh(); goto case 40;}
else {t.kind = noSym; break;}
case 40:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 41;}
else {t.kind = noSym; break;}
case 41:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 41;}
else if (ch == 'D' || ch == 'd') {AddCh(); goto case 42;}
else {t.kind = 3; break;}
case 42:
{t.kind = 3; break;}
case 43:
if (ch <= 9 || ch >= 11 && ch <= 12 || ch >= 14 && ch <= '!' || ch >= '#' && ch <= '[' || ch >= ']' && ch <= 65535) {AddCh(); goto case 43;}
else if (ch == '"') {AddCh(); goto case 44;}
else if (ch == 92) {AddCh(); goto case 64;}
else {t.kind = noSym; break;}
case 44:
{t.kind = 4; break;}
case 45:
{t.kind = 30; break;}
case 46:
{t.kind = 31; break;}
case 47:
{t.kind = 33; break;}
case 48:
{t.kind = 35; break;}
case 49:
{t.kind = 36; break;}
case 50:
{t.kind = 37; break;}
case 51:
{t.kind = 38; break;}
case 52:
{t.kind = 40; break;}
case 53:
{t.kind = 42; break;}
case 54:
{t.kind = 43; break;}
case 55:
{t.kind = 44; break;}
case 56:
{t.kind = 45; break;}
case 57:
{t.kind = 46; break;}
case 58:
{t.kind = 47; break;}
case 59:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 59;}
else if (ch == '.') {apx++; AddCh(); goto case 65;}
else if (ch == 'E' || ch == 'e') {AddCh(); goto case 39;}
else if (ch == 'D' || ch == 'd') {AddCh(); goto case 42;}
else {t.kind = 2; break;}
case 60:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 59;}
else if (ch == '.') {apx++; AddCh(); goto case 65;}
else if (ch == 'X' || ch == 'x') {AddCh(); goto case 28;}
else if (ch == 'E' || ch == 'e') {AddCh(); goto case 39;}
else if (ch == 'D' || ch == 'd') {AddCh(); goto case 42;}
else {t.kind = 2; break;}
case 61:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 31;}
else {t.kind = 32; break;}
case 62:
if (ch == '=') {AddCh(); goto case 47;}
else {t.kind = 29; break;}
case 63:
if (ch == '=') {AddCh(); goto case 48;}
else {t.kind = 34; break;}
case 64:
if (ch == '"' || ch == 39 || ch == '0' || ch == 92 || ch >= 'a' && ch <= 'b' || ch == 'f' || ch == 'n' || ch == 'r' || ch == 't' || ch == 'v') {AddCh(); goto case 43;}
else {t.kind = noSym; break;}
case 65:
if (ch <= '/' || ch >= ':' && ch <= 65535) {apx++; AddCh(); goto case 30;}
else if (ch >= '0' && ch <= '9') {apx = 0; AddCh(); goto case 35;}
else {t.kind = noSym; break;}
case 66:
{t.kind = 48; break;}
case 67:
{t.kind = 49; break;}
case 68:
{t.kind = 50; break;}
case 69:
{t.kind = 51; break;}
case 70:
if (ch == '=') {AddCh(); goto case 67;}
else {t.kind = 39; break;}
case 71:
if (ch == '=') {AddCh(); goto case 66;}
else {t.kind = 41; break;}
}
t.val = new String(tval, 0, tlen);
return t;
}
// get the next token (possibly a token already seen during peeking)
public Token Scan () {
if (tokens.next == null) {
return NextToken();
} else {
pt = tokens = tokens.next;
return tokens;
}
}
// peek for the next token, ignore pragmas
public Token Peek () {
if (pt.next == null) {
do {
pt = pt.next = NextToken();
} while (pt.kind > maxT); // skip pragmas
} else {
do {
pt = pt.next;
} while (pt.kind > maxT);
}
return pt;
}
// make sure that peeking starts at the current scan position
public void ResetPeek () { pt = tokens; }
} // end Scanner
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.HttpServerUtility.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web
{
sealed public partial class HttpServerUtility
{
#region Methods and constructors
public void ClearError ()
{
}
public Object CreateObject (string progID)
{
Contract.Ensures (Contract.Result<System.Object>() != null);
return default(Object);
}
public Object CreateObject (Type type)
{
Contract.Requires (type != null);
Contract.Ensures (Contract.Result<System.Object>() != null);
return default(Object);
}
public Object CreateObjectFromClsid (string clsid)
{
Contract.Ensures (Contract.Result<System.Object>() != null);
return default(Object);
}
public void Execute (string path, bool preserveForm)
{
}
public void Execute (IHttpHandler handler, TextWriter writer, bool preserveForm)
{
}
public void Execute (string path, TextWriter writer, bool preserveForm)
{
}
public void Execute (string path, TextWriter writer)
{
}
public void Execute (string path)
{
}
public Exception GetLastError ()
{
return default(Exception);
}
public void HtmlDecode (string s, TextWriter output)
{
}
[Pure]
public string HtmlDecode (string s)
{
Contract.Ensures(s == null || Contract.Result<string>() != null);
return default(string);
}
[Pure]
public string HtmlEncode (string s)
{
Contract.Ensures(s == null || Contract.Result<string>() != null);
return default(string);
}
public void HtmlEncode (string s, TextWriter output)
{
}
public string MapPath (string path)
{
Contract.Ensures(path == null || Contract.Result<string>() != null);
return default(string);
}
public void Transfer (IHttpHandler handler, bool preserveForm)
{
}
public void Transfer (string path)
{
}
public void Transfer (string path, bool preserveForm)
{
}
public void TransferRequest (string path)
{
}
public void TransferRequest (string path, bool preserveForm, string method, System.Collections.Specialized.NameValueCollection headers)
{
}
public void TransferRequest (string path, bool preserveForm)
{
}
public string UrlDecode (string s)
{
return default(string);
}
public void UrlDecode (string s, TextWriter output)
{
Contract.Requires (output != null);
}
public string UrlEncode (string s)
{
return default(string);
}
public void UrlEncode (string s, TextWriter output)
{
Contract.Requires (output != null);
}
[Pure]
public string UrlPathEncode (string s)
{
Contract.Ensures(Contract.Result<string>() != null || s == null);
return default(string);
}
public static byte[] UrlTokenDecode (string input)
{
return default(byte[]);
}
public static string UrlTokenEncode (byte[] input)
{
return default(string);
}
#endregion
#region Properties and indexers
public string MachineName
{
get
{
return default(string);
}
}
public int ScriptTimeout
{
get
{
return default(int);
}
set
{
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Internal.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
public sealed class ConditionalWeakTable<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
where TKey : class
where TValue : class?
{
// Lifetimes of keys and values:
// Inserting a key and value into the dictonary will not
// prevent the key from dying, even if the key is strongly reachable
// from the value. Once the key dies, the dictionary automatically removes
// the key/value entry.
//
// Thread safety guarantees:
// ConditionalWeakTable is fully thread-safe and requires no
// additional locking to be done by callers.
//
// OOM guarantees:
// Will not corrupt unmanaged handle table on OOM. No guarantees
// about managed weak table consistency. Native handles reclamation
// may be delayed until appdomain shutdown.
private const int InitialCapacity = 8; // Initial length of the table. Must be a power of two.
private readonly object _lock; // This lock protects all mutation of data in the table. Readers do not take this lock.
private volatile Container _container; // The actual storage for the table; swapped out as the table grows.
private int _activeEnumeratorRefCount; // The number of outstanding enumerators on the table
public ConditionalWeakTable()
{
_lock = new object();
_container = new Container(this);
}
/// <summary>Gets the value of the specified key.</summary>
/// <param name="key">key of the value to find. Cannot be null.</param>
/// <param name="value">
/// If the key is found, contains the value associated with the key upon method return.
/// If the key is not found, contains default(TValue).
/// </param>
/// <returns>Returns "true" if key was found, "false" otherwise.</returns>
/// <remarks>
/// The key may get garbaged collected during the TryGetValue operation. If so, TryGetValue
/// may at its discretion, return "false" and set "value" to the default (as if the key was not present.)
/// </remarks>
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
if (key is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return _container.TryGetValueWorker(key, out value);
}
/// <summary>Adds a key to the table.</summary>
/// <param name="key">key to add. May not be null.</param>
/// <param name="value">value to associate with key.</param>
/// <remarks>
/// If the key is already entered into the dictionary, this method throws an exception.
/// The key may get garbage collected during the Add() operation. If so, Add()
/// has the right to consider any prior entries successfully removed and add a new entry without
/// throwing an exception.
/// </remarks>
public void Add(TKey key, TValue value)
{
if (key is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
lock (_lock)
{
int entryIndex = _container.FindEntry(key, out _);
if (entryIndex != -1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
CreateEntry(key, value);
}
}
/// <summary>Adds the key and value if the key doesn't exist, or updates the existing key's value if it does exist.</summary>
/// <param name="key">key to add or update. May not be null.</param>
/// <param name="value">value to associate with key.</param>
public void AddOrUpdate(TKey key, TValue value)
{
if (key is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
lock (_lock)
{
int entryIndex = _container.FindEntry(key, out _);
// if we found a key we should just update, if no we should create a new entry.
if (entryIndex != -1)
{
_container.UpdateValue(entryIndex, value);
}
else
{
CreateEntry(key, value);
}
}
}
/// <summary>Removes a key and its value from the table.</summary>
/// <param name="key">key to remove. May not be null.</param>
/// <returns>true if the key is found and removed. Returns false if the key was not in the dictionary.</returns>
/// <remarks>
/// The key may get garbage collected during the Remove() operation. If so,
/// Remove() will not fail or throw, however, the return value can be either true or false
/// depending on who wins the race.
/// </remarks>
public bool Remove(TKey key)
{
if (key is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
lock (_lock)
{
return _container.Remove(key);
}
}
/// <summary>Clear all the key/value pairs</summary>
public void Clear()
{
lock (_lock)
{
// To clear, we would prefer to simply drop the existing container
// and replace it with an empty one, as that's overall more efficient.
// However, if there are any active enumerators, we don't want to do
// that as it will end up removing all of the existing entries and
// allowing new items to be added at the same indices when the container
// is filled and replaced, and one of the guarantees we try to make with
// enumeration is that new items added after enumeration starts won't be
// included in the enumeration. As such, if there are active enumerators,
// we simply use the container's removal functionality to remove all of the
// keys; then when the table is resized, if there are still active enumerators,
// these empty slots will be maintained.
if (_activeEnumeratorRefCount > 0)
{
_container.RemoveAllKeys();
}
else
{
_container = new Container(this);
}
}
}
/// <summary>
/// Atomically searches for a specified key in the table and returns the corresponding value.
/// If the key does not exist in the table, the method invokes a callback method to create a
/// value that is bound to the specified key.
/// </summary>
/// <param name="key">key of the value to find. Cannot be null.</param>
/// <param name="createValueCallback">callback that creates value for key. Cannot be null.</param>
/// <returns></returns>
/// <remarks>
/// If multiple threads try to initialize the same key, the table may invoke createValueCallback
/// multiple times with the same key. Exactly one of these calls will succeed and the returned
/// value of that call will be the one added to the table and returned by all the racing GetValue() calls.
/// This rule permits the table to invoke createValueCallback outside the internal table lock
/// to prevent deadlocks.
/// </remarks>
public TValue GetValue(TKey key, CreateValueCallback createValueCallback)
{
// key is validated by TryGetValue
if (createValueCallback is null)
{
throw new ArgumentNullException(nameof(createValueCallback));
}
return TryGetValue(key, out TValue existingValue) ?
existingValue :
GetValueLocked(key, createValueCallback);
}
private TValue GetValueLocked(TKey key, CreateValueCallback createValueCallback)
{
// If we got here, the key was not in the table. Invoke the callback (outside the lock)
// to generate the new value for the key.
TValue newValue = createValueCallback(key);
lock (_lock)
{
// Now that we've taken the lock, must recheck in case we lost a race to add the key.
if (_container.TryGetValueWorker(key, out TValue existingValue))
{
return existingValue;
}
else
{
// Verified in-lock that we won the race to add the key. Add it now.
CreateEntry(key, newValue);
return newValue;
}
}
}
/// <summary>
/// Helper method to call GetValue without passing a creation delegate. Uses Activator.CreateInstance
/// to create new instances as needed. If TValue does not have a default constructor, this will throw.
/// </summary>
/// <param name="key">key of the value to find. Cannot be null.</param>
public TValue GetOrCreateValue(TKey key) => GetValue(key, _ => Activator.CreateInstance<TValue>());
public delegate TValue CreateValueCallback(TKey key);
/// <summary>Gets an enumerator for the table.</summary>
/// <remarks>
/// The returned enumerator will not extend the lifetime of
/// any object pairs in the table, other than the one that's Current. It will not return entries
/// that have already been collected, nor will it return entries added after the enumerator was
/// retrieved. It may not return all entries that were present when the enumerat was retrieved,
/// however, such as not returning entries that were collected or removed after the enumerator
/// was retrieved but before they were enumerated.
/// </remarks>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
lock (_lock)
{
Container c = _container;
return c is null || c.FirstFreeEntry == 0 ?
((IEnumerable<KeyValuePair<TKey, TValue>>)Array.Empty<KeyValuePair<TKey, TValue>>()).GetEnumerator() :
new Enumerator(this);
}
}
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<KeyValuePair<TKey, TValue>>)this).GetEnumerator();
/// <summary>Provides an enumerator for the table.</summary>
private sealed class Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
// The enumerator would ideally hold a reference to the Container and the end index within that
// container. However, the safety of the CWT depends on the only reference to the Container being
// from the CWT itself; the Container then employs a two-phase finalization scheme, where the first
// phase nulls out that parent CWT's reference, guaranteeing that the second time it's finalized there
// can be no other existing references to it in use that would allow for concurrent usage of the
// native handles with finalization. We would break that if we allowed this Enumerator to hold a
// reference to the Container. Instead, the Enumerator holds a reference to the CWT rather than to
// the Container, and it maintains the CWT._activeEnumeratorRefCount field to track whether there
// are outstanding enumerators that have yet to be disposed/finalized. If there aren't any, the CWT
// behaves as it normally does. If there are, certain operations are affected, in particular resizes.
// Normally when the CWT is resized, it enumerates the contents of the table looking for indices that
// contain entries which have been collected or removed, and it frees those up, effectively moving
// down all subsequent entries in the container (not in the existing container, but in a replacement).
// This, however, would cause the enumerator's understanding of indices to break. So, as long as
// there is any outstanding enumerator, no compaction is performed.
private ConditionalWeakTable<TKey, TValue>? _table; // parent table, set to null when disposed
private readonly int _maxIndexInclusive; // last index in the container that should be enumerated
private int _currentIndex = -1; // the current index into the container
private KeyValuePair<TKey, TValue> _current; // the current entry set by MoveNext and returned from Current
public Enumerator(ConditionalWeakTable<TKey, TValue> table)
{
Debug.Assert(table != null, "Must provide a valid table");
Debug.Assert(Monitor.IsEntered(table._lock), "Must hold the _lock lock to construct the enumerator");
Debug.Assert(table._container != null, "Should not be used on a finalized table");
Debug.Assert(table._container.FirstFreeEntry > 0, "Should have returned an empty enumerator instead");
// Store a reference to the parent table and increase its active enumerator count.
_table = table;
Debug.Assert(table._activeEnumeratorRefCount >= 0, "Should never have a negative ref count before incrementing");
table._activeEnumeratorRefCount++;
// Store the max index to be enumerated.
_maxIndexInclusive = table._container.FirstFreeEntry - 1;
_currentIndex = -1;
}
~Enumerator()
{
Dispose();
}
public void Dispose()
{
// Use an interlocked operation to ensure that only one thread can get access to
// the _table for disposal and thus only decrement the ref count once.
ConditionalWeakTable<TKey, TValue>? table = Interlocked.Exchange(ref _table, null);
if (table != null)
{
// Ensure we don't keep the last current alive unnecessarily
_current = default;
// Decrement the ref count that was incremented when constructed
lock (table._lock)
{
table._activeEnumeratorRefCount--;
Debug.Assert(table._activeEnumeratorRefCount >= 0, "Should never have a negative ref count after decrementing");
}
// Finalization is purely to decrement the ref count. We can suppress it now.
GC.SuppressFinalize(this);
}
}
public bool MoveNext()
{
// Start by getting the current table. If it's already been disposed, it will be null.
ConditionalWeakTable<TKey, TValue>? table = _table;
if (table != null)
{
// Once have the table, we need to lock to synchronize with other operations on
// the table, like adding.
lock (table._lock)
{
// From the table, we have to get the current container. This could have changed
// since we grabbed the enumerator, but the index-to-pair mapping should not have
// due to there being at least one active enumerator. If the table (or rather its
// container at the time) has already been finalized, this will be null.
Container c = table._container;
if (c != null)
{
// We have the container. Find the next entry to return, if there is one.
// We need to loop as we may try to get an entry that's already been removed
// or collected, in which case we try again.
while (_currentIndex < _maxIndexInclusive)
{
_currentIndex++;
if (c.TryGetEntry(_currentIndex, out TKey? key, out TValue value))
{
_current = new KeyValuePair<TKey, TValue>(key, value);
return true;
}
}
}
}
}
// Nothing more to enumerate.
return false;
}
public KeyValuePair<TKey, TValue> Current
{
get
{
if (_currentIndex < 0)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _current;
}
}
object? IEnumerator.Current => Current;
public void Reset() { }
}
/// <summary>Worker for adding a new key/value pair. Will resize the container if it is full.</summary>
/// <param name="key"></param>
/// <param name="value"></param>
private void CreateEntry(TKey key, TValue value)
{
Debug.Assert(Monitor.IsEntered(_lock));
Debug.Assert(key != null); // key already validated as non-null and not already in table.
Container c = _container;
if (!c.HasCapacity)
{
_container = c = c.Resize();
}
c.CreateEntryNoResize(key, value);
}
private static bool IsPowerOfTwo(int value) => (value > 0) && ((value & (value - 1)) == 0);
//--------------------------------------------------------------------------------------------
// Entry can be in one of four states:
//
// - Unused (stored with an index _firstFreeEntry and above)
// depHnd.IsAllocated == false
// hashCode == <dontcare>
// next == <dontcare>)
//
// - Used with live key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry)
// depHnd.IsAllocated == true, depHnd.GetPrimary() != null
// hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & int.MaxValue
// next links to next Entry in bucket.
//
// - Used with dead key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry)
// depHnd.IsAllocated == true, depHnd.GetPrimary() is null
// hashCode == <notcare>
// next links to next Entry in bucket.
//
// - Has been removed from the table (by a call to Remove)
// depHnd.IsAllocated == true, depHnd.GetPrimary() == <notcare>
// hashCode == -1
// next links to next Entry in bucket.
//
// The only difference between "used with live key" and "used with dead key" is that
// depHnd.GetPrimary() returns null. The transition from "used with live key" to "used with dead key"
// happens asynchronously as a result of normal garbage collection. The dictionary itself
// receives no notification when this happens.
//
// When the dictionary grows the _entries table, it scours it for expired keys and does not
// add those to the new container.
//--------------------------------------------------------------------------------------------
private struct Entry
{
public DependentHandle depHnd; // Holds key and value using a weak reference for the key and a strong reference
// for the value that is traversed only if the key is reachable without going through the value.
public int HashCode; // Cached copy of key's hashcode
public int Next; // Index of next entry, -1 if last
}
/// <summary>
/// Container holds the actual data for the table. A given instance of Container always has the same capacity. When we need
/// more capacity, we create a new Container, copy the old one into the new one, and discard the old one. This helps enable lock-free
/// reads from the table, as readers never need to deal with motion of entries due to rehashing.
/// </summary>
private sealed class Container
{
private readonly ConditionalWeakTable<TKey, TValue> _parent; // the ConditionalWeakTable with which this container is associated
private int[] _buckets; // _buckets[hashcode & (_buckets.Length - 1)] contains index of the first entry in bucket (-1 if empty)
private Entry[] _entries; // the table entries containing the stored dependency handles
private int _firstFreeEntry; // _firstFreeEntry < _entries.Length => table has capacity, entries grow from the bottom of the table.
private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock.
private bool _finalized; // set to true when initially finalized
private volatile object? _oldKeepAlive; // used to ensure the next allocated container isn't finalized until this one is GC'd
internal Container(ConditionalWeakTable<TKey, TValue> parent)
{
Debug.Assert(parent != null);
Debug.Assert(IsPowerOfTwo(InitialCapacity));
int size = InitialCapacity;
_buckets = new int[size];
for (int i = 0; i < _buckets.Length; i++)
{
_buckets[i] = -1;
}
_entries = new Entry[size];
// Only store the parent after all of the allocations have happened successfully.
// Otherwise, as part of growing or clearing the container, we could end up allocating
// a new Container that fails (OOMs) part way through construction but that gets finalized
// and ends up clearing out some other container present in the associated CWT.
_parent = parent;
}
private Container(ConditionalWeakTable<TKey, TValue> parent, int[] buckets, Entry[] entries, int firstFreeEntry)
{
Debug.Assert(parent != null);
Debug.Assert(buckets != null);
Debug.Assert(entries != null);
Debug.Assert(buckets.Length == entries.Length);
Debug.Assert(IsPowerOfTwo(buckets.Length));
_parent = parent;
_buckets = buckets;
_entries = entries;
_firstFreeEntry = firstFreeEntry;
}
internal bool HasCapacity => _firstFreeEntry < _entries.Length;
internal int FirstFreeEntry => _firstFreeEntry;
/// <summary>Worker for adding a new key/value pair. Container must NOT be full.</summary>
internal void CreateEntryNoResize(TKey key, TValue value)
{
Debug.Assert(key != null); // key already validated as non-null and not already in table.
Debug.Assert(HasCapacity);
VerifyIntegrity();
_invalid = true;
int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue;
int newEntry = _firstFreeEntry++;
_entries[newEntry].HashCode = hashCode;
_entries[newEntry].depHnd = new DependentHandle(key, value);
int bucket = hashCode & (_buckets.Length - 1);
_entries[newEntry].Next = _buckets[bucket];
// This write must be volatile, as we may be racing with concurrent readers. If they see
// the new entry, they must also see all of the writes earlier in this method.
Volatile.Write(ref _buckets[bucket], newEntry);
_invalid = false;
}
/// <summary>Worker for finding a key/value pair. Must hold _lock.</summary>
internal bool TryGetValueWorker(TKey key, [MaybeNullWhen(false)] out TValue value)
{
Debug.Assert(key != null); // Key already validated as non-null
int entryIndex = FindEntry(key, out object? secondary);
value = Unsafe.As<TValue>(secondary);
return entryIndex != -1;
}
/// <summary>
/// Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found.").
/// Must hold _lock, or be prepared to retry the search while holding _lock.
/// </summary>
internal int FindEntry(TKey key, out object? value)
{
Debug.Assert(key != null); // Key already validated as non-null.
int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue;
int bucket = hashCode & (_buckets.Length - 1);
for (int entriesIndex = Volatile.Read(ref _buckets[bucket]); entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
{
if (_entries[entriesIndex].HashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out value) == key)
{
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
return entriesIndex;
}
}
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
value = null;
return -1;
}
/// <summary>Gets the entry at the specified entry index.</summary>
internal bool TryGetEntry(int index, [NotNullWhen(true)] out TKey? key, [MaybeNullWhen(false)] out TValue value)
{
if (index < _entries.Length)
{
object? oKey = _entries[index].depHnd.GetPrimaryAndSecondary(out object? oValue);
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
if (oKey != null)
{
key = Unsafe.As<TKey>(oKey);
value = Unsafe.As<TValue>(oValue);
return true;
}
}
key = default;
value = default!;
return false;
}
/// <summary>Removes all of the keys in the table.</summary>
internal void RemoveAllKeys()
{
for (int i = 0; i < _firstFreeEntry; i++)
{
RemoveIndex(i);
}
}
/// <summary>Removes the specified key from the table, if it exists.</summary>
internal bool Remove(TKey key)
{
VerifyIntegrity();
int entryIndex = FindEntry(key, out _);
if (entryIndex != -1)
{
RemoveIndex(entryIndex);
return true;
}
return false;
}
private void RemoveIndex(int entryIndex)
{
Debug.Assert(entryIndex >= 0 && entryIndex < _firstFreeEntry);
ref Entry entry = ref _entries[entryIndex];
// We do not free the handle here, as we may be racing with readers who already saw the hash code.
// Instead, we simply overwrite the entry's hash code, so subsequent reads will ignore it.
// The handle will be free'd in Container's finalizer, after the table is resized or discarded.
Volatile.Write(ref entry.HashCode, -1);
// Also, clear the key to allow GC to collect objects pointed to by the entry
entry.depHnd.SetPrimary(null);
}
internal void UpdateValue(int entryIndex, TValue newValue)
{
Debug.Assert(entryIndex != -1);
VerifyIntegrity();
_invalid = true;
_entries[entryIndex].depHnd.SetSecondary(newValue);
_invalid = false;
}
/// <summary>Resize, and scrub expired keys off bucket lists. Must hold _lock.</summary>
/// <remarks>
/// _firstEntry is less than _entries.Length on exit, that is, the table has at least one free entry.
/// </remarks>
internal Container Resize()
{
Debug.Assert(!HasCapacity);
bool hasExpiredEntries = false;
int newSize = _buckets.Length;
if (_parent is null || _parent._activeEnumeratorRefCount == 0)
{
// If any expired or removed keys exist, we won't resize.
// If there any active enumerators, though, we don't want
// to compact and thus have no expired entries.
for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
{
ref Entry entry = ref _entries[entriesIndex];
if (entry.HashCode == -1)
{
// the entry was removed
hasExpiredEntries = true;
break;
}
if (entry.depHnd.IsAllocated && entry.depHnd.GetPrimary() is null)
{
// the entry has expired
hasExpiredEntries = true;
break;
}
}
}
if (!hasExpiredEntries)
{
// Not necessary to check for overflow here, the attempt to allocate new arrays will throw
newSize = _buckets.Length * 2;
}
return Resize(newSize);
}
internal Container Resize(int newSize)
{
Debug.Assert(newSize >= _buckets.Length);
Debug.Assert(IsPowerOfTwo(newSize));
// Reallocate both buckets and entries and rebuild the bucket and entries from scratch.
// This serves both to scrub entries with expired keys and to put the new entries in the proper bucket.
int[] newBuckets = new int[newSize];
for (int bucketIndex = 0; bucketIndex < newBuckets.Length; bucketIndex++)
{
newBuckets[bucketIndex] = -1;
}
Entry[] newEntries = new Entry[newSize];
int newEntriesIndex = 0;
bool activeEnumerators = _parent != null && _parent._activeEnumeratorRefCount > 0;
// Migrate existing entries to the new table.
if (activeEnumerators)
{
// There's at least one active enumerator, which means we don't want to
// remove any expired/removed entries, in order to not affect existing
// entries indices. Copy over the entries while rebuilding the buckets list,
// as the buckets are dependent on the buckets list length, which is changing.
for (; newEntriesIndex < _entries.Length; newEntriesIndex++)
{
ref Entry oldEntry = ref _entries[newEntriesIndex];
ref Entry newEntry = ref newEntries[newEntriesIndex];
int hashCode = oldEntry.HashCode;
newEntry.HashCode = hashCode;
newEntry.depHnd = oldEntry.depHnd;
int bucket = hashCode & (newBuckets.Length - 1);
newEntry.Next = newBuckets[bucket];
newBuckets[bucket] = newEntriesIndex;
}
}
else
{
// There are no active enumerators, which means we want to compact by
// removing expired/removed entries.
for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
{
ref Entry oldEntry = ref _entries[entriesIndex];
int hashCode = oldEntry.HashCode;
DependentHandle depHnd = oldEntry.depHnd;
if (hashCode != -1 && depHnd.IsAllocated)
{
if (depHnd.GetPrimary() != null)
{
ref Entry newEntry = ref newEntries[newEntriesIndex];
// Entry is used and has not expired. Link it into the appropriate bucket list.
newEntry.HashCode = hashCode;
newEntry.depHnd = depHnd;
int bucket = hashCode & (newBuckets.Length - 1);
newEntry.Next = newBuckets[bucket];
newBuckets[bucket] = newEntriesIndex;
newEntriesIndex++;
}
else
{
// Pretend the item was removed, so that this container's finalizer
// will clean up this dependent handle.
Volatile.Write(ref oldEntry.HashCode, -1);
}
}
}
}
// Create the new container. We want to transfer the responsibility of freeing the handles from
// the old container to the new container, and also ensure that the new container isn't finalized
// while the old container may still be in use. As such, we store a reference from the old container
// to the new one, which will keep the new container alive as long as the old one is.
var newContainer = new Container(_parent!, newBuckets, newEntries, newEntriesIndex);
if (activeEnumerators)
{
// If there are active enumerators, both the old container and the new container may be storing
// the same entries with -1 hash codes, which the finalizer will clean up even if the container
// is not the active container for the table. To prevent that, we want to stop the old container
// from being finalized, as it no longer has any responsibility for any cleanup.
GC.SuppressFinalize(this);
}
_oldKeepAlive = newContainer; // once this is set, the old container's finalizer will not free transferred dependent handles
GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
return newContainer;
}
private void VerifyIntegrity()
{
if (_invalid)
{
throw new InvalidOperationException(SR.InvalidOperation_CollectionCorrupted);
}
}
~Container()
{
// Skip doing anything if the container is invalid, including if somehow
// the container object was allocated but its associated table never set.
if (_invalid || _parent is null)
{
return;
}
// It's possible that the ConditionalWeakTable could have been resurrected, in which case code could
// be accessing this Container as it's being finalized. We don't support usage after finalization,
// but we also don't want to potentially corrupt state by allowing dependency handles to be used as
// or after they've been freed. To avoid that, if it's at all possible that another thread has a
// reference to this container via the CWT, we remove such a reference and then re-register for
// finalization: the next time around, we can be sure that no references remain to this and we can
// clean up the dependency handles without fear of corruption.
if (!_finalized)
{
_finalized = true;
lock (_parent._lock)
{
if (_parent._container == this)
{
_parent._container = null!;
}
}
GC.ReRegisterForFinalize(this); // next time it's finalized, we'll be sure there are no remaining refs
return;
}
Entry[] entries = _entries;
_invalid = true;
_entries = null!;
_buckets = null!;
if (entries != null)
{
for (int entriesIndex = 0; entriesIndex < entries.Length; entriesIndex++)
{
// We need to free handles in two cases:
// - If this container still owns the dependency handle (meaning ownership hasn't been transferred
// to another container that replaced this one), then it should be freed.
// - If this container had the entry removed, then even if in general ownership was transferred to
// another container, removed entries are not, therefore this container must free them.
if (_oldKeepAlive is null || entries[entriesIndex].HashCode == -1)
{
entries[entriesIndex].depHnd.Free();
}
}
}
}
}
}
}
| |
// 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.Generic;
using System.Runtime.InteropServices;
using Internal.TypeSystem;
using Internal.TypeSystem.Interop;
using Debug = System.Diagnostics.Debug;
namespace Internal.IL.Stubs
{
public enum StructMarshallingThunkType : byte
{
ManagedToNative = 1,
NativeToManage = 2,
Cleanup = 4
}
public struct InlineArrayCandidate
{
public readonly MetadataType ElementType;
public readonly uint Length;
public InlineArrayCandidate(MetadataType type, uint length)
{
ElementType = type;
Length = length;
}
}
public partial class StructMarshallingThunk : ILStubMethod
{
internal readonly MetadataType ManagedType;
internal readonly NativeStructType NativeType;
internal readonly StructMarshallingThunkType ThunkType;
private InteropStateManager _interopStateManager;
private TypeDesc _owningType;
private Marshaller[] _marshallers;
public StructMarshallingThunk(TypeDesc owningType, MetadataType managedType, StructMarshallingThunkType thunkType, InteropStateManager interopStateManager)
{
_owningType = owningType;
ManagedType = managedType;
_interopStateManager = interopStateManager;
NativeType = _interopStateManager.GetStructMarshallingNativeType(managedType);
ThunkType = thunkType;
_marshallers = InitializeMarshallers();
}
public override TypeSystemContext Context
{
get
{
return ManagedType.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _owningType;
}
}
private MethodSignature _signature;
public override MethodSignature Signature
{
get
{
if (_signature == null)
{
TypeDesc[] parameters;
if (ThunkType == StructMarshallingThunkType.Cleanup)
{
parameters = new TypeDesc[] {
NativeType.MakeByRefType()
};
}
else
{
parameters = new TypeDesc[] {
ManagedType.MakeByRefType(),
NativeType.MakeByRefType()
};
}
_signature = new MethodSignature(MethodSignatureFlags.Static, 0, Context.GetWellKnownType(WellKnownType.Void), parameters);
}
return _signature;
}
}
private string NamePrefix
{
get
{
switch (ThunkType)
{
case StructMarshallingThunkType.ManagedToNative:
return "ManagedToNative";
case StructMarshallingThunkType.NativeToManage:
return "NativeToManaged";
case StructMarshallingThunkType.Cleanup:
return "Cleanup";
default:
System.Diagnostics.Debug.Assert(false, "Unexpected Struct marshalling thunk type");
return string.Empty;
}
}
}
public override string Name
{
get
{
return NamePrefix + "__" + ((MetadataType)ManagedType).Name;
}
}
private Marshaller[] InitializeMarshallers()
{
Debug.Assert(_interopStateManager != null);
MarshalAsDescriptor[] marshalAsDescriptors = ((MetadataType)ManagedType).GetFieldMarshalAsDescriptors();
Marshaller[] marshallers = new Marshaller[marshalAsDescriptors.Length];
PInvokeFlags flags = new PInvokeFlags();
if (ManagedType.PInvokeStringFormat == PInvokeStringFormat.UnicodeClass || ManagedType.PInvokeStringFormat == PInvokeStringFormat.AutoClass)
{
flags.CharSet = CharSet.Unicode;
}
else
{
flags.CharSet = CharSet.Ansi;
}
int index = 0;
foreach (FieldDesc field in ManagedType.GetFields())
{
if (field.IsStatic)
{
continue;
}
marshallers[index] = Marshaller.CreateMarshaller(field.FieldType,
MarshallerType.Field,
marshalAsDescriptors[index],
(ThunkType == StructMarshallingThunkType.NativeToManage) ? MarshalDirection.Reverse : MarshalDirection.Forward,
marshallers,
_interopStateManager,
index,
flags,
isIn: true, /* Struct fields are considered as IN within the helper*/
isOut: false,
isReturn: false);
index++;
}
return marshallers;
}
private MethodIL EmitMarshallingIL(PInvokeILCodeStreams pInvokeILCodeStreams)
{
ILEmitter emitter = pInvokeILCodeStreams.Emitter;
IEnumerator<FieldDesc> nativeEnumerator = NativeType.GetFields().GetEnumerator();
int index = 0;
foreach (var managedField in ManagedType.GetFields())
{
if (managedField.IsStatic)
{
continue;
}
bool notEmpty = nativeEnumerator.MoveNext();
Debug.Assert(notEmpty == true);
var nativeField = nativeEnumerator.Current;
Debug.Assert(nativeField != null);
bool isInlineArray = nativeField.FieldType is InlineArrayType;
//
// Field marshallers expects the value of the fields to be
// loaded on the stack. We load the value on the stack
// before calling the marshallers.
// Only exception is ByValArray marshallers. Since they can
// only be used for field marshalling, they load/store values
// directly from arguments.
//
if (isInlineArray)
{
var byValMarshaller = _marshallers[index++] as ByValArrayMarshaller;
Debug.Assert(byValMarshaller != null);
byValMarshaller.EmitMarshallingIL(pInvokeILCodeStreams, managedField, nativeField);
}
else
{
if (ThunkType == StructMarshallingThunkType.ManagedToNative)
{
LoadFieldValueFromArg(0, managedField, pInvokeILCodeStreams);
}
else if (ThunkType == StructMarshallingThunkType.NativeToManage)
{
LoadFieldValueFromArg(1, nativeField, pInvokeILCodeStreams);
}
_marshallers[index++].EmitMarshallingIL(pInvokeILCodeStreams);
if (ThunkType == StructMarshallingThunkType.ManagedToNative)
{
StoreFieldValueFromArg(1, nativeField, pInvokeILCodeStreams);
}
else if (ThunkType == StructMarshallingThunkType.NativeToManage)
{
StoreFieldValueFromArg(0, managedField, pInvokeILCodeStreams);
}
}
}
Debug.Assert(!nativeEnumerator.MoveNext());
pInvokeILCodeStreams.UnmarshallingCodestream.Emit(ILOpcode.ret);
return emitter.Link(this);
}
private MethodIL EmitCleanupIL(PInvokeILCodeStreams pInvokeILCodeStreams)
{
ILEmitter emitter = pInvokeILCodeStreams.Emitter;
ILCodeStream codeStream = pInvokeILCodeStreams.MarshallingCodeStream;
IEnumerator<FieldDesc> nativeEnumerator = NativeType.GetFields().GetEnumerator();
int index = 0;
foreach (var managedField in ManagedType.GetFields())
{
if (managedField.IsStatic)
{
continue;
}
bool notEmpty = nativeEnumerator.MoveNext();
Debug.Assert(notEmpty == true);
var nativeField = nativeEnumerator.Current;
Debug.Assert(nativeField != null);
if (_marshallers[index].CleanupRequired)
{
LoadFieldValueFromArg(0, nativeField, pInvokeILCodeStreams);
_marshallers[index].EmitElementCleanup(codeStream, emitter);
}
index++;
}
pInvokeILCodeStreams.UnmarshallingCodestream.Emit(ILOpcode.ret);
return emitter.Link(this);
}
public override MethodIL EmitIL()
{
try
{
PInvokeILCodeStreams pInvokeILCodeStreams = new PInvokeILCodeStreams();
if (ThunkType == StructMarshallingThunkType.Cleanup)
{
return EmitCleanupIL(pInvokeILCodeStreams);
}
else
{
return EmitMarshallingIL(pInvokeILCodeStreams);
}
}
catch (NotSupportedException)
{
string message = "Struct '" + ((MetadataType)ManagedType).Name +
"' requires non-trivial marshalling that is not yet supported by this compiler.";
return MarshalHelpers.EmitExceptionBody(message, this);
}
catch (InvalidProgramException ex)
{
Debug.Assert(!String.IsNullOrEmpty(ex.Message));
return MarshalHelpers.EmitExceptionBody(ex.Message, this);
}
}
/// <summary>
/// Loads the value of field of a struct at argument index argIndex to stack
/// </summary>
private void LoadFieldValueFromArg(int argIndex, FieldDesc field, PInvokeILCodeStreams pInvokeILCodeStreams)
{
ILCodeStream stream = pInvokeILCodeStreams.MarshallingCodeStream;
ILEmitter emitter = pInvokeILCodeStreams.Emitter;
stream.EmitLdArg(argIndex);
stream.Emit(ILOpcode.ldfld, emitter.NewToken(field));
}
private void StoreFieldValueFromArg(int argIndex, FieldDesc field, PInvokeILCodeStreams pInvokeILCodeStreams)
{
ILCodeStream stream = pInvokeILCodeStreams.MarshallingCodeStream;
ILEmitter emitter = pInvokeILCodeStreams.Emitter;
Internal.IL.Stubs.ILLocalVariable var = emitter.NewLocal(field.FieldType);
stream.EmitStLoc(var);
stream.EmitLdArg(argIndex);
stream.EmitLdLoc(var);
stream.Emit(ILOpcode.stfld, emitter.NewToken(field));
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Config
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Xml;
using NLog.Common;
using NLog.Filters;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using NLog.LayoutRenderers;
using NLog.Time;
#if SILVERLIGHT
// ReSharper disable once RedundantUsingDirective
using System.Windows;
#endif
/// <summary>
/// A class for configuring NLog through an XML configuration file
/// (App.config style or App.nlog style).
/// </summary>
public class XmlLoggingConfiguration : LoggingConfiguration
{
#region private fields
private readonly Dictionary<string, bool> visitedFile = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private string originalFileName;
private ConfigurationItemFactory ConfigurationItemFactory
{
get { return ConfigurationItemFactory.Default; }
}
#endregion
#region contructors
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
public XmlLoggingConfiguration(string fileName)
{
using (XmlReader reader = XmlReader.Create(fileName))
{
this.Initialize(reader, fileName, false);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
public XmlLoggingConfiguration(string fileName, bool ignoreErrors)
{
using (XmlReader reader = XmlReader.Create(fileName))
{
this.Initialize(reader, fileName, ignoreErrors);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName)
{
this.Initialize(reader, fileName, false);
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors)
{
this.Initialize(reader, fileName, ignoreErrors);
}
#if !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
internal XmlLoggingConfiguration(XmlElement element, string fileName)
{
using (var stringReader = new StringReader(element.OuterXml))
{
XmlReader reader = XmlReader.Create(stringReader);
this.Initialize(reader, fileName, false);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
/// <param name="ignoreErrors">If set to <c>true</c> errors will be ignored during file processing.</param>
internal XmlLoggingConfiguration(XmlElement element, string fileName, bool ignoreErrors)
{
using (var stringReader = new StringReader(element.OuterXml))
{
XmlReader reader = XmlReader.Create(stringReader);
this.Initialize(reader, fileName, ignoreErrors);
}
}
#endif
#endregion
#region public properties
#if !SILVERLIGHT
/// <summary>
/// Gets the default <see cref="LoggingConfiguration" /> object by parsing
/// the application configuration file (<c>app.exe.config</c>).
/// </summary>
public static LoggingConfiguration AppConfig
{
get
{
object o = System.Configuration.ConfigurationManager.GetSection("nlog");
return o as LoggingConfiguration;
}
}
#endif
/// <summary>
/// Did the <see cref="Initialize"/> Succeeded? <c>true</c>= success, <c>false</c>= error, <c>null</c> = initialize not started yet.
/// </summary>
public bool? InitializeSucceeded { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether the configuration files
/// should be watched for changes and reloaded automatically when changed.
/// </summary>
public bool AutoReload { get; set; }
/// <summary>
/// Gets the collection of file names which should be watched for changes by NLog.
/// This is the list of configuration files processed.
/// If the <c>autoReload</c> attribute is not set it returns empty collection.
/// </summary>
public override IEnumerable<string> FileNamesToWatch
{
get
{
if (this.AutoReload)
{
return this.visitedFile.Keys;
}
return new string[0];
}
}
#endregion
#region public methods
/// <summary>
/// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object.
/// </summary>
/// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns>
public override LoggingConfiguration Reload()
{
return new XmlLoggingConfiguration(this.originalFileName);
}
#endregion
private static bool IsTargetElement(string name)
{
return name.Equals("target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target", StringComparison.OrdinalIgnoreCase);
}
private static bool IsTargetRefElement(string name)
{
return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Remove all spaces, also in between text.
/// </summary>
/// <param name="s">text</param>
/// <returns>text without spaces</returns>
/// <remarks>Tabs and other whitespace is not removed!</remarks>
private static string CleanSpaces(string s)
{
s = s.Replace(" ", string.Empty); // get rid of the whitespace
return s;
}
/// <summary>
/// Remove the namespace (before :)
/// </summary>
/// <example>
/// x:a, will be a
/// </example>
/// <param name="attributeValue"></param>
/// <returns></returns>
private static string StripOptionalNamespacePrefix(string attributeValue)
{
if (attributeValue == null)
{
return null;
}
int p = attributeValue.IndexOf(':');
if (p < 0)
{
return attributeValue;
}
return attributeValue.Substring(p + 1);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")]
private static Target WrapWithAsyncTargetWrapper(Target target)
{
var asyncTargetWrapper = new AsyncTargetWrapper();
asyncTargetWrapper.WrappedTarget = target;
asyncTargetWrapper.Name = target.Name;
target.Name = target.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name);
target = asyncTargetWrapper;
return target;
}
/// <summary>
/// Initializes the configuration.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
{
try
{
InitializeSucceeded = null;
reader.MoveToContent();
var content = new NLogXmlElement(reader);
if (fileName != null)
{
#if SILVERLIGHT
string key = fileName;
#else
string key = Path.GetFullPath(fileName);
#endif
this.visitedFile[key] = true;
this.originalFileName = fileName;
this.ParseTopLevel(content, Path.GetDirectoryName(fileName));
InternalLogger.Info("Configured from an XML element in {0}...", fileName);
}
else
{
this.ParseTopLevel(content, null);
}
InitializeSucceeded = true;
}
catch (Exception exception)
{
InitializeSucceeded = false;
if (exception.MustBeRethrown())
{
throw;
}
NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);
if (!ignoreErrors)
{
if (LogManager.ThrowExceptions)
{
throw ConfigException;
}
else
{
InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
}
}
else
{
InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
}
}
}
private void ConfigureFromFile(string fileName)
{
#if SILVERLIGHT
// file names are relative to XAP
string key = fileName;
#else
string key = Path.GetFullPath(fileName);
#endif
if (this.visitedFile.ContainsKey(key))
{
return;
}
this.visitedFile[key] = true;
this.ParseTopLevel(new NLogXmlElement(fileName), Path.GetDirectoryName(fileName));
}
#region parse methods
/// <summary>
/// Parse the root
/// </summary>
/// <param name="content"></param>
/// <param name="baseDirectory">path to directory of config file.</param>
private void ParseTopLevel(NLogXmlElement content, string baseDirectory)
{
content.AssertName("nlog", "configuration");
switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "CONFIGURATION":
this.ParseConfigurationElement(content, baseDirectory);
break;
case "NLOG":
this.ParseNLogElement(content, baseDirectory);
break;
}
}
/// <summary>
/// Parse {configuration} xml element.
/// </summary>
/// <param name="configurationElement"></param>
/// <param name="baseDirectory">path to directory of config file.</param>
private void ParseConfigurationElement(NLogXmlElement configurationElement, string baseDirectory)
{
InternalLogger.Trace("ParseConfigurationElement");
configurationElement.AssertName("configuration");
foreach (var el in configurationElement.Elements("nlog"))
{
this.ParseNLogElement(el, baseDirectory);
}
}
/// <summary>
/// Parse {NLog} xml element.
/// </summary>
/// <param name="nlogElement"></param>
/// <param name="baseDirectory">path to directory of config file.</param>
private void ParseNLogElement(NLogXmlElement nlogElement, string baseDirectory)
{
InternalLogger.Trace("ParseNLogElement");
nlogElement.AssertName("nlog");
if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false))
{
this.DefaultCultureInfo = CultureInfo.InvariantCulture;
}
#pragma warning disable 618
this.ExceptionLoggingOldStyle = nlogElement.GetOptionalBooleanAttribute("exceptionLoggingOldStyle", false);
#pragma warning restore 618
this.AutoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", false);
LogManager.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions);
InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole);
InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError);
InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile);
InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name));
LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name));
var children = nlogElement.Children;
//first load the extensions, as the can be used in other elements (targets etc)
var extensionsChilds = children.Where(child => child.LocalName.Equals("EXTENSIONS", StringComparison.InvariantCultureIgnoreCase));
foreach (var extensionsChild in extensionsChilds)
{
this.ParseExtensionsElement(extensionsChild, baseDirectory);
}
//parse all other direct elements
foreach (var child in children)
{
switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "EXTENSIONS":
//already parsed
break;
case "INCLUDE":
this.ParseIncludeElement(child, baseDirectory);
break;
case "APPENDERS":
case "TARGETS":
this.ParseTargetsElement(child);
break;
case "VARIABLE":
this.ParseVariableElement(child);
break;
case "RULES":
this.ParseRulesElement(child, this.LoggingRules);
break;
case "TIME":
this.ParseTimeElement(child);
break;
default:
InternalLogger.Warn("Skipping unknown node: {0}", child.LocalName);
break;
}
}
}
/// <summary>
/// Parse {Rules} xml element
/// </summary>
/// <param name="rulesElement"></param>
/// <param name="rulesCollection">Rules are added to this parameter.</param>
private void ParseRulesElement(NLogXmlElement rulesElement, IList<LoggingRule> rulesCollection)
{
InternalLogger.Trace("ParseRulesElement");
rulesElement.AssertName("rules");
foreach (var loggerElement in rulesElement.Elements("logger"))
{
this.ParseLoggerElement(loggerElement, rulesCollection);
}
}
/// <summary>
/// Parse {Logger} xml element
/// </summary>
/// <param name="loggerElement"></param>
/// <param name="rulesCollection">Rules are added to this parameter.</param>
private void ParseLoggerElement(NLogXmlElement loggerElement, IList<LoggingRule> rulesCollection)
{
loggerElement.AssertName("logger");
var namePattern = loggerElement.GetOptionalAttribute("name", "*");
var enabled = loggerElement.GetOptionalBooleanAttribute("enabled", true);
if (!enabled)
{
InternalLogger.Debug("The logger named '{0}' are disabled");
return;
}
var rule = new LoggingRule();
string appendTo = loggerElement.GetOptionalAttribute("appendTo", null);
if (appendTo == null)
{
appendTo = loggerElement.GetOptionalAttribute("writeTo", null);
}
rule.LoggerNamePattern = namePattern;
if (appendTo != null)
{
foreach (string t in appendTo.Split(','))
{
string targetName = t.Trim();
Target target = FindTargetByName(targetName);
if (target != null)
{
rule.Targets.Add(target);
}
else
{
throw new NLogConfigurationException("Target " + targetName + " not found.");
}
}
}
rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false);
string levelString;
if (loggerElement.AttributeValues.TryGetValue("level", out levelString))
{
LogLevel level = LogLevel.FromString(levelString);
rule.EnableLoggingForLevel(level);
}
else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString))
{
levelString = CleanSpaces(levelString);
string[] tokens = levelString.Split(',');
foreach (string s in tokens)
{
if (!string.IsNullOrEmpty(s))
{
LogLevel level = LogLevel.FromString(s);
rule.EnableLoggingForLevel(level);
}
}
}
else
{
int minLevel = 0;
int maxLevel = LogLevel.MaxLevel.Ordinal;
string minLevelString;
string maxLevelString;
if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString))
{
minLevel = LogLevel.FromString(minLevelString).Ordinal;
}
if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString))
{
maxLevel = LogLevel.FromString(maxLevelString).Ordinal;
}
for (int i = minLevel; i <= maxLevel; ++i)
{
rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
}
}
foreach (var child in loggerElement.Children)
{
switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "FILTERS":
this.ParseFilters(rule, child);
break;
case "LOGGER":
this.ParseLoggerElement(child, rule.ChildRules);
break;
}
}
rulesCollection.Add(rule);
}
private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement)
{
filtersElement.AssertName("filters");
foreach (var filterElement in filtersElement.Children)
{
string name = filterElement.LocalName;
Filter filter = this.ConfigurationItemFactory.Filters.CreateInstance(name);
this.ConfigureObjectFromAttributes(filter, filterElement, false);
rule.Filters.Add(filter);
}
}
private void ParseVariableElement(NLogXmlElement variableElement)
{
variableElement.AssertName("variable");
string name = variableElement.GetRequiredAttribute("name");
string value = this.ExpandSimpleVariables(variableElement.GetRequiredAttribute("value"));
this.Variables[name] = value;
}
private void ParseTargetsElement(NLogXmlElement targetsElement)
{
targetsElement.AssertName("targets", "appenders");
bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false);
NLogXmlElement defaultWrapperElement = null;
var typeNameToDefaultTargetParameters = new Dictionary<string, NLogXmlElement>();
foreach (var targetElement in targetsElement.Children)
{
string name = targetElement.LocalName;
string type = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null));
switch (name.ToUpper(CultureInfo.InvariantCulture))
{
case "DEFAULT-WRAPPER":
defaultWrapperElement = targetElement;
break;
case "DEFAULT-TARGET-PARAMETERS":
if (type == null)
{
throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
}
typeNameToDefaultTargetParameters[type] = targetElement;
break;
case "TARGET":
case "APPENDER":
case "WRAPPER":
case "WRAPPER-TARGET":
case "COMPOUND-TARGET":
if (type == null)
{
throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
}
Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(type);
NLogXmlElement defaults;
if (typeNameToDefaultTargetParameters.TryGetValue(type, out defaults))
{
this.ParseTargetElement(newTarget, defaults);
}
this.ParseTargetElement(newTarget, targetElement);
if (asyncWrap)
{
newTarget = WrapWithAsyncTargetWrapper(newTarget);
}
if (defaultWrapperElement != null)
{
newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement);
}
InternalLogger.Info("Adding target {0}", newTarget);
AddTarget(newTarget.Name, newTarget);
break;
}
}
}
private void ParseTargetElement(Target target, NLogXmlElement targetElement)
{
var compound = target as CompoundTargetBase;
var wrapper = target as WrapperTargetBase;
this.ConfigureObjectFromAttributes(target, targetElement, true);
foreach (var childElement in targetElement.Children)
{
string name = childElement.LocalName;
if (compound != null)
{
if (IsTargetRefElement(name))
{
string targetName = childElement.GetRequiredAttribute("name");
Target newTarget = this.FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
compound.Targets.Add(newTarget);
continue;
}
if (IsTargetElement(name))
{
string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));
Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(type);
if (newTarget != null)
{
this.ParseTargetElement(newTarget, childElement);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
compound.Targets.Add(newTarget);
}
continue;
}
}
if (wrapper != null)
{
if (IsTargetRefElement(name))
{
string targetName = childElement.GetRequiredAttribute("name");
Target newTarget = this.FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
wrapper.WrappedTarget = newTarget;
continue;
}
if (IsTargetElement(name))
{
string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));
Target newTarget = this.ConfigurationItemFactory.Targets.CreateInstance(type);
if (newTarget != null)
{
this.ParseTargetElement(newTarget, childElement);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
if (wrapper.WrappedTarget != null)
{
throw new NLogConfigurationException("Wrapped target already defined.");
}
wrapper.WrappedTarget = newTarget;
}
continue;
}
}
this.SetPropertyFromElement(target, childElement);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification = "Need to load external assembly.")]
private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory)
{
extensionsElement.AssertName("extensions");
foreach (var addElement in extensionsElement.Elements("add"))
{
string prefix = addElement.GetOptionalAttribute("prefix", null);
if (prefix != null)
{
prefix = prefix + ".";
}
string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null));
if (type != null)
{
this.ConfigurationItemFactory.RegisterType(Type.GetType(type, true), prefix);
}
string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null);
if (assemblyFile != null)
{
try
{
#if SILVERLIGHT
var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative));
var assemblyPart = new AssemblyPart();
Assembly asm = assemblyPart.Load(si.Stream);
#else
string fullFileName = Path.Combine(baseDirectory, assemblyFile);
InternalLogger.Info("Loading assembly file: {0}", fullFileName);
Assembly asm = Assembly.LoadFrom(fullFileName);
#endif
this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error loading extensions: {0}", exception);
if (LogManager.ThrowExceptions)
{
throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
}
}
continue;
}
string assemblyName = addElement.GetOptionalAttribute("assembly", null);
if (assemblyName != null)
{
try
{
InternalLogger.Info("Loading assembly name: {0}", assemblyName);
#if SILVERLIGHT
var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative));
var assemblyPart = new AssemblyPart();
Assembly asm = assemblyPart.Load(si.Stream);
#else
Assembly asm = Assembly.Load(assemblyName);
#endif
this.ConfigurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error loading extensions: {0}", exception);
if (LogManager.ThrowExceptions)
{
throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
}
}
continue;
}
}
}
private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory)
{
includeElement.AssertName("include");
string newFileName = includeElement.GetRequiredAttribute("file");
try
{
newFileName = this.ExpandSimpleVariables(newFileName);
newFileName = SimpleLayout.Evaluate(newFileName);
if (baseDirectory != null)
{
newFileName = Path.Combine(baseDirectory, newFileName);
}
#if SILVERLIGHT
newFileName = newFileName.Replace("\\", "/");
if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null)
#else
if (File.Exists(newFileName))
#endif
{
InternalLogger.Debug("Including file '{0}'", newFileName);
this.ConfigureFromFile(newFileName);
}
else
{
throw new FileNotFoundException("Included file not found: " + newFileName);
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error when including '{0}' {1}", newFileName, exception);
if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false))
{
return;
}
throw new NLogConfigurationException("Error when including: " + newFileName, exception);
}
}
private void ParseTimeElement(NLogXmlElement timeElement)
{
timeElement.AssertName("time");
string type = timeElement.GetRequiredAttribute("type");
TimeSource newTimeSource = this.ConfigurationItemFactory.TimeSources.CreateInstance(type);
this.ConfigureObjectFromAttributes(newTimeSource, timeElement, true);
InternalLogger.Info("Selecting time source {0}", newTimeSource);
TimeSource.Current = newTimeSource;
}
#endregion
private void SetPropertyFromElement(object o, NLogXmlElement element)
{
if (this.AddArrayItemFromElement(o, element))
{
return;
}
if (this.SetLayoutFromElement(o, element))
{
return;
}
PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandSimpleVariables(element.Value), this.ConfigurationItemFactory);
}
private bool AddArrayItemFromElement(object o, NLogXmlElement element)
{
string name = element.LocalName;
PropertyInfo propInfo;
if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo))
{
return false;
}
Type elementType = PropertyHelper.GetArrayItemType(propInfo);
if (elementType != null)
{
IList propertyValue = (IList)propInfo.GetValue(o, null);
object arrayItem = FactoryHelper.CreateInstance(elementType);
this.ConfigureObjectFromAttributes(arrayItem, element, true);
this.ConfigureObjectFromElement(arrayItem, element);
propertyValue.Add(arrayItem);
return true;
}
return false;
}
private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType)
{
foreach (var kvp in element.AttributeValues)
{
string childName = kvp.Key;
string childValue = kvp.Value;
if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase))
{
continue;
}
PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandSimpleVariables(childValue), this.ConfigurationItemFactory);
}
}
private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement)
{
PropertyInfo targetPropertyInfo;
string name = layoutElement.LocalName;
// if property exists
if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo))
{
// and is a Layout
if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType))
{
string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null));
// and 'type' attribute has been specified
if (layoutTypeName != null)
{
// configure it from current element
Layout layout = this.ConfigurationItemFactory.Layouts.CreateInstance(this.ExpandSimpleVariables(layoutTypeName));
this.ConfigureObjectFromAttributes(layout, layoutElement, true);
this.ConfigureObjectFromElement(layout, layoutElement);
targetPropertyInfo.SetValue(o, layout, null);
return true;
}
}
}
return false;
}
private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element)
{
foreach (var child in element.Children)
{
this.SetPropertyFromElement(targetObject, child);
}
}
private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters)
{
string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type"));
Target wrapperTargetInstance = this.ConfigurationItemFactory.Targets.CreateInstance(wrapperType);
WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper.");
}
this.ParseTargetElement(wrapperTargetInstance, defaultParameters);
while (wtb.WrappedTarget != null)
{
wtb = wtb.WrappedTarget as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper.");
}
}
wtb.WrappedTarget = t;
wrapperTargetInstance.Name = t.Name;
t.Name = t.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name);
return wrapperTargetInstance;
}
/// <summary>
/// Replace a simple variable with a value. The orginal value is removed and thus we cannot redo this in a later stage.
///
/// Use for that: <see cref="VariableLayoutRenderer"/>
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private string ExpandSimpleVariables(string input)
{
string output = input;
// TODO - make this case-insensitive, will probably require a different approach
foreach (var kvp in this.Variables)
{
var layout = kvp.Value;
//this value is set from xml and that's a string. Because of that, we can use SimpleLayout here.
if (layout != null) output = output.Replace("${" + kvp.Key + "}", layout.OriginalText);
}
return output;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Compute.V1
{
/// <summary>Settings for <see cref="RegionInstancesClient"/> instances.</summary>
public sealed partial class RegionInstancesSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="RegionInstancesSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="RegionInstancesSettings"/>.</returns>
public static RegionInstancesSettings GetDefault() => new RegionInstancesSettings();
/// <summary>Constructs a new <see cref="RegionInstancesSettings"/> object with default settings.</summary>
public RegionInstancesSettings()
{
}
private RegionInstancesSettings(RegionInstancesSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
BulkInsertSettings = existing.BulkInsertSettings;
BulkInsertOperationsSettings = existing.BulkInsertOperationsSettings.Clone();
OnCopy(existing);
}
partial void OnCopy(RegionInstancesSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RegionInstancesClient.BulkInsert</c> and <c>RegionInstancesClient.BulkInsertAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings BulkInsertSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// Long Running Operation settings for calls to <c>RegionInstancesClient.BulkInsert</c> and
/// <c>RegionInstancesClient.BulkInsertAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings BulkInsertOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="RegionInstancesSettings"/> object.</returns>
public RegionInstancesSettings Clone() => new RegionInstancesSettings(this);
}
/// <summary>
/// Builder class for <see cref="RegionInstancesClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class RegionInstancesClientBuilder : gaxgrpc::ClientBuilderBase<RegionInstancesClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public RegionInstancesSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public RegionInstancesClientBuilder()
{
UseJwtAccessWithScopes = RegionInstancesClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref RegionInstancesClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<RegionInstancesClient> task);
/// <summary>Builds the resulting client.</summary>
public override RegionInstancesClient Build()
{
RegionInstancesClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<RegionInstancesClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<RegionInstancesClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private RegionInstancesClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return RegionInstancesClient.Create(callInvoker, Settings);
}
private async stt::Task<RegionInstancesClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return RegionInstancesClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => RegionInstancesClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => RegionInstancesClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => RegionInstancesClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => ComputeRestAdapter.ComputeAdapter;
}
/// <summary>RegionInstances client wrapper, for convenient use.</summary>
/// <remarks>
/// The RegionInstances API.
/// </remarks>
public abstract partial class RegionInstancesClient
{
/// <summary>
/// The default endpoint for the RegionInstances service, which is a host of "compute.googleapis.com" and a port
/// of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "compute.googleapis.com:443";
/// <summary>The default RegionInstances scopes.</summary>
/// <remarks>
/// The default RegionInstances scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/compute</description></item>
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="RegionInstancesClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="RegionInstancesClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="RegionInstancesClient"/>.</returns>
public static stt::Task<RegionInstancesClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new RegionInstancesClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="RegionInstancesClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="RegionInstancesClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="RegionInstancesClient"/>.</returns>
public static RegionInstancesClient Create() => new RegionInstancesClientBuilder().Build();
/// <summary>
/// Creates a <see cref="RegionInstancesClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="RegionInstancesSettings"/>.</param>
/// <returns>The created <see cref="RegionInstancesClient"/>.</returns>
internal static RegionInstancesClient Create(grpccore::CallInvoker callInvoker, RegionInstancesSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
RegionInstances.RegionInstancesClient grpcClient = new RegionInstances.RegionInstancesClient(callInvoker);
return new RegionInstancesClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC RegionInstances client</summary>
public virtual RegionInstances.RegionInstancesClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates multiple instances in a given region. Count specifies the number of instances to create.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Operation, Operation> BulkInsert(BulkInsertRegionInstanceRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates multiple instances in a given region. Count specifies the number of instances to create.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> BulkInsertAsync(BulkInsertRegionInstanceRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates multiple instances in a given region. Count specifies the number of instances to create.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> BulkInsertAsync(BulkInsertRegionInstanceRequest request, st::CancellationToken cancellationToken) =>
BulkInsertAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>BulkInsert</c>.</summary>
public virtual lro::OperationsClient BulkInsertOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>BulkInsert</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<Operation, Operation> PollOnceBulkInsert(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Operation, Operation>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), BulkInsertOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of
/// <c>BulkInsert</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> PollOnceBulkInsertAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Operation, Operation>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), BulkInsertOperationsClient, callSettings);
/// <summary>
/// Creates multiple instances in a given region. Count specifies the number of instances to create.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="region">
/// The name of the region for this request.
/// </param>
/// <param name="bulkInsertInstanceResourceResource">
/// The body resource for this request
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Operation, Operation> BulkInsert(string project, string region, BulkInsertInstanceResource bulkInsertInstanceResourceResource, gaxgrpc::CallSettings callSettings = null) =>
BulkInsert(new BulkInsertRegionInstanceRequest
{
BulkInsertInstanceResourceResource = gax::GaxPreconditions.CheckNotNull(bulkInsertInstanceResourceResource, nameof(bulkInsertInstanceResourceResource)),
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
}, callSettings);
/// <summary>
/// Creates multiple instances in a given region. Count specifies the number of instances to create.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="region">
/// The name of the region for this request.
/// </param>
/// <param name="bulkInsertInstanceResourceResource">
/// The body resource for this request
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> BulkInsertAsync(string project, string region, BulkInsertInstanceResource bulkInsertInstanceResourceResource, gaxgrpc::CallSettings callSettings = null) =>
BulkInsertAsync(new BulkInsertRegionInstanceRequest
{
BulkInsertInstanceResourceResource = gax::GaxPreconditions.CheckNotNull(bulkInsertInstanceResourceResource, nameof(bulkInsertInstanceResourceResource)),
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)),
}, callSettings);
/// <summary>
/// Creates multiple instances in a given region. Count specifies the number of instances to create.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="region">
/// The name of the region for this request.
/// </param>
/// <param name="bulkInsertInstanceResourceResource">
/// The body resource for this request
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> BulkInsertAsync(string project, string region, BulkInsertInstanceResource bulkInsertInstanceResourceResource, st::CancellationToken cancellationToken) =>
BulkInsertAsync(project, region, bulkInsertInstanceResourceResource, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>RegionInstances client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// The RegionInstances API.
/// </remarks>
public sealed partial class RegionInstancesClientImpl : RegionInstancesClient
{
private readonly gaxgrpc::ApiCall<BulkInsertRegionInstanceRequest, Operation> _callBulkInsert;
/// <summary>
/// Constructs a client wrapper for the RegionInstances service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="RegionInstancesSettings"/> used within this client.</param>
public RegionInstancesClientImpl(RegionInstances.RegionInstancesClient grpcClient, RegionInstancesSettings settings)
{
GrpcClient = grpcClient;
RegionInstancesSettings effectiveSettings = settings ?? RegionInstancesSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
BulkInsertOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClientForRegionOperations(), effectiveSettings.BulkInsertOperationsSettings);
_callBulkInsert = clientHelper.BuildApiCall<BulkInsertRegionInstanceRequest, Operation>(grpcClient.BulkInsertAsync, grpcClient.BulkInsert, effectiveSettings.BulkInsertSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("region", request => request.Region);
Modify_ApiCall(ref _callBulkInsert);
Modify_BulkInsertApiCall(ref _callBulkInsert);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_BulkInsertApiCall(ref gaxgrpc::ApiCall<BulkInsertRegionInstanceRequest, Operation> call);
partial void OnConstruction(RegionInstances.RegionInstancesClient grpcClient, RegionInstancesSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC RegionInstances client</summary>
public override RegionInstances.RegionInstancesClient GrpcClient { get; }
partial void Modify_BulkInsertRegionInstanceRequest(ref BulkInsertRegionInstanceRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>The long-running operations client for <c>BulkInsert</c>.</summary>
public override lro::OperationsClient BulkInsertOperationsClient { get; }
/// <summary>
/// Creates multiple instances in a given region. Count specifies the number of instances to create.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override lro::Operation<Operation, Operation> BulkInsert(BulkInsertRegionInstanceRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_BulkInsertRegionInstanceRequest(ref request, ref callSettings);
Operation response = _callBulkInsert.Sync(request, callSettings);
GetRegionOperationRequest pollRequest = GetRegionOperationRequest.FromInitialResponse(response);
request.PopulatePollRequestFields(pollRequest);
return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), BulkInsertOperationsClient);
}
/// <summary>
/// Creates multiple instances in a given region. Count specifies the number of instances to create.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override async stt::Task<lro::Operation<Operation, Operation>> BulkInsertAsync(BulkInsertRegionInstanceRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_BulkInsertRegionInstanceRequest(ref request, ref callSettings);
Operation response = await _callBulkInsert.Async(request, callSettings).ConfigureAwait(false);
GetRegionOperationRequest pollRequest = GetRegionOperationRequest.FromInitialResponse(response);
request.PopulatePollRequestFields(pollRequest);
return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), BulkInsertOperationsClient);
}
}
public static partial class RegionInstances
{
public partial class RegionInstancesClient
{
/// <summary>
/// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as
/// this client, delegating to RegionOperations.
/// </summary>
/// <returns>A new Operations client for the same target as this client.</returns>
public virtual lro::Operations.OperationsClient CreateOperationsClientForRegionOperations() =>
RegionOperations.RegionOperationsClient.CreateOperationsClient(CallInvoker);
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Samples.Controls.SearchPersist.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using Novell.Directory.Ldap;
using Novell.Directory.Ldap.Controls;
namespace Samples.Controls
{
class SearchPersist
{
const double TIME_OUT_IN_MINUTES = 0.5;
static DateTime timeOut;
static void Main(string[] args)
{
if ( args.Length != 5)
{
Console.WriteLine("Usage: mono SearchPersist <host name> <ldap port> <login dn>" + " <password> <search base>" );
Console.WriteLine("Example: mono SearchPersist Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"");
return;
}
int ldapVersion = LdapConnection.Ldap_V3;
String ldapHost = args[0];
int ldapPort = Convert.ToInt32(args[1]);;
String loginDN = args[2];
String password = args[3];
String searchBase = args[4];
LdapSearchQueue queue = null;
LdapSearchConstraints constraints;
LdapPersistSearchControl psCtrl;
LdapConnection lc = new LdapConnection();
constraints = new LdapSearchConstraints();
try
{
// connect to the server
lc.Connect( ldapHost, ldapPort );
// authenticate to the server
lc.Bind(ldapVersion, loginDN, password);
//Create the persistent search control
psCtrl = new LdapPersistSearchControl(
LdapPersistSearchControl.ANY, // any change
true, //only get changes
true, //return entry change controls
true); //control is critcal
// add the persistent search control to the search constraints
constraints.setControls( psCtrl );
// perform the search with no attributes returned
String[] noAttrs = {LdapConnection.NO_ATTRS};
queue = lc.Search(
searchBase, // container to search
LdapConnection.SCOPE_SUB, // search container's subtree
"(objectClass=*)", // search filter, all objects
noAttrs, // don't return attributes
false, // return attrs and values, ignored
null, // use default search queue
constraints); // use default search constraints
}
catch( LdapException e )
{
Console.WriteLine( "Error: " + e.ToString() );
try { lc.Disconnect(); }
catch(LdapException e2) { }
Environment.Exit(1);
}
catch(Exception e)
{
Console.WriteLine( "Error: " + e.Message );
return;
}
Console.WriteLine("Monitoring the events for {0} minutes..", TIME_OUT_IN_MINUTES );
Console.WriteLine();
//Set the timeout value
timeOut= DateTime.Now.AddMinutes(TIME_OUT_IN_MINUTES);
try
{
//Monitor till the timeout happens
while (DateTime.Now.CompareTo(timeOut) < 0)
{
if (!checkForAChange(queue))
break;
System.Threading.Thread.Sleep(10);
}
}
catch (System.IO.IOException e)
{
System.Console.Out.WriteLine(e.Message);
}
catch (System.Threading.ThreadInterruptedException e)
{
}
//Disconnect from the server before exiting
try
{
lc.Abandon(queue); //abandon the search
lc.Disconnect();
}
catch (LdapException e)
{
Console.Out.WriteLine();
Console.Out.WriteLine("Error: " + e.ToString());
}
Environment.Exit(0);
}
/// <summary> Check the queue for a response. If a response has been received,
/// print the response information.
/// </summary>
static private bool checkForAChange(LdapSearchQueue queue)
{
LdapMessage message;
bool result = true;
try
{
//check if a response has been received so we don't block
//when calling getResponse()
if (queue.isResponseReceived())
{
message = queue.getResponse();
if (message != null)
{
// is the response a search result reference?
if (message is LdapSearchResultReference)
{
String[] urls = ((LdapSearchResultReference) message).Referrals;
Console.Out.WriteLine("\nSearch result references:");
for (int i = 0; i < urls.Length; i++)
Console.Out.WriteLine(urls[i]);
}
// is the response a search result?
else if (message is LdapSearchResult)
{
LdapControl[] controls = message.Controls;
for (int i = 0; i < controls.Length; i++)
{
if (controls[i] is LdapEntryChangeControl)
{
LdapEntryChangeControl ecCtrl = (LdapEntryChangeControl) controls[i];
int changeType = ecCtrl.ChangeType;
Console.Out.WriteLine("\n\nchange type: " + getChangeTypeString(changeType));
if (changeType == LdapPersistSearchControl.MODDN)
Console.Out.WriteLine("Prev. DN: " + ecCtrl.PreviousDN);
if (ecCtrl.HasChangeNumber)
Console.Out.WriteLine("Change Number: " + ecCtrl.ChangeNumber);
LdapEntry entry = ((LdapSearchResult) message).Entry;
Console.Out.WriteLine("entry: " + entry.DN);
}
}
}
// the message is a search response
else
{
LdapResponse response = (LdapResponse) message;
int resultCode = response.ResultCode;
if (resultCode == LdapException.SUCCESS)
{
Console.Out.WriteLine("\nUnexpected success response.");
result = false;
}
else if (resultCode == LdapException.REFERRAL)
{
String[] urls = ((LdapResponse) message).Referrals;
Console.Out.WriteLine("\n\nReferrals:");
for (int i = 0; i < urls.Length; i++)
Console.Out.WriteLine(urls[i]);
}
else
{
Console.Out.WriteLine("Persistent search failed.");
throw new LdapException(response.ErrorMessage, resultCode, response.MatchedDN);
}
}
}
}
}
catch (LdapException e)
{
Console.Out.WriteLine("Error: " + e.ToString());
result = false;
}
return result;
}
/// <summary> Return a string indicating the type of change represented by the
/// changeType parameter.
/// </summary>
private static String getChangeTypeString(int changeType)
{
String changeTypeString;
switch (changeType)
{
case LdapPersistSearchControl.ADD:
changeTypeString = "ADD";
break;
case LdapPersistSearchControl.MODIFY:
changeTypeString = "MODIFY";
break;
case LdapPersistSearchControl.MODDN:
changeTypeString = "MODDN";
break;
case LdapPersistSearchControl.DELETE:
changeTypeString = "DELETE";
break;
default:
changeTypeString = "Unknown change type: " + changeType.ToString();
break;
}
return changeTypeString;
}
} //end class SearchPersist
}
| |
/*
* REST API Documentation for Schoolbus
*
* API Sample
*
* OpenAPI spec version: v1
*
*
*/
using Newtonsoft.Json;
using SchoolBusAPI.Models;
using SchoolBusAPI.ViewModels;
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using Xunit;
namespace SchoolBusAPI.Test
{
public class RoleApiIntegrationTest : ApiIntegrationTestBase
{
[Fact]
/// <summary>
/// Basic Integration test for Roles
/// </summary>
public async void TestRolesBasic()
{
string initialName = "InitialName";
string changedName = "ChangedName";
// first test the POST.
var request = new HttpRequestMessage(HttpMethod.Post, "/api/roles");
// create a new object.
RoleViewModel role = new RoleViewModel();
role.Name = initialName;
string jsonString = role.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
role = JsonConvert.DeserializeObject<RoleViewModel>(jsonString);
// get the id
var id = role.Id;
// change the name
role.Name = changedName;
// now do an update.
request = new HttpRequestMessage(HttpMethod.Put, "/api/roles/" + id);
request.Content = new StringContent(role.ToJson(), Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// do a get.
request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + id);
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
role = JsonConvert.DeserializeObject<RoleViewModel>(jsonString);
// verify the change went through.
Assert.Equal(role.Name, changedName);
// do a delete.
request = new HttpRequestMessage(HttpMethod.Post, "/api/roles/" + id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
}
[Fact]
/// <summary>
/// Test Users and Roles
/// </summary>
public async void TestUserRoles()
{
// first create a role.
string initialName = "InitialName";
var request = new HttpRequestMessage(HttpMethod.Post, "/api/roles");
RoleViewModel role = new RoleViewModel();
role.Name = initialName;
role.Description = "test";
string jsonString = role.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
role = JsonConvert.DeserializeObject<RoleViewModel>(jsonString);
// get the role id
var role_id = role.Id;
// now create a user.
request = new HttpRequestMessage(HttpMethod.Post, "/api/users");
UserViewModel user = new UserViewModel();
user.GivenName = initialName;
jsonString = user.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
user = JsonConvert.DeserializeObject<UserViewModel>(jsonString);
// get the user id
var user_id = user.Id;
// now add the user to the role.
UserRoleViewModel userRole = new UserRoleViewModel();
userRole.RoleId = role_id;
userRole.UserId = user_id;
userRole.EffectiveDate = DateTime.UtcNow;
UserRoleViewModel[] items = new UserRoleViewModel[1];
items[0] = userRole;
// send the request.
request = new HttpRequestMessage(HttpMethod.Put, "/api/roles/" + role_id + "/users");
jsonString = JsonConvert.SerializeObject(items, Formatting.Indented);
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// if we do a get we should get the same items.
request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + role_id + "/users");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
User[] userRolesResponse = JsonConvert.DeserializeObject<User[]>(jsonString);
Assert.Equal(items[0].UserId, userRolesResponse[0].Id);
// cleanup
// Delete user
request = new HttpRequestMessage(HttpMethod.Post, "/api/users/" + user_id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + user_id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
// Delete role
request = new HttpRequestMessage(HttpMethod.Post, "/api/roles/" + role_id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + role_id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
}
[Fact]
/// <summary>
/// Test Users and Roles
/// </summary>
public async void TestRolePermissions()
{
// first create a role.
string initialName = "InitialName";
var request = new HttpRequestMessage(HttpMethod.Post, "/api/roles");
RoleViewModel roleViewModel = new RoleViewModel();
roleViewModel.Name = initialName;
string jsonString = roleViewModel.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
roleViewModel = JsonConvert.DeserializeObject<RoleViewModel>(jsonString);
// get the role id
var role_id = roleViewModel.Id;
// now create a permission.
request = new HttpRequestMessage(HttpMethod.Post, "/api/permissions");
Permission permission = new Permission();
permission.Name = initialName;
jsonString = permission.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
permission = JsonConvert.DeserializeObject<Permission>(jsonString);
// get the permission id
var permission_id = permission.Id;
// now add the permission to the role.
request = new HttpRequestMessage(HttpMethod.Post, "/api/roles/" + role_id + "/permissions");
jsonString = JsonConvert.SerializeObject(permission, Formatting.Indented);
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// if we do a get we should get the same items.
request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + role_id + "/permissions");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
Permission[] rolePermissionsResponse = JsonConvert.DeserializeObject<Permission[]>(jsonString);
Assert.Equal(permission.Code, rolePermissionsResponse[0].Code);
Assert.Equal(permission.Name, rolePermissionsResponse[0].Name);
// test the put.
Permission[] items = new Permission[1];
items[0] = permission;
request = new HttpRequestMessage(HttpMethod.Put, "/api/roles/" + role_id + "/permissions");
jsonString = JsonConvert.SerializeObject(items, Formatting.Indented);
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// cleanup
// Delete permission
request = new HttpRequestMessage(HttpMethod.Post, "/api/permissions/" + permission_id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/permissions/" + permission_id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
// Delete role
request = new HttpRequestMessage(HttpMethod.Post, "/api/roles/" + role_id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + role_id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
}
}
}
| |
using System;
using System.Linq.Expressions;
namespace AutoMapper
{
/// <summary>
/// Mapping configuration options for non-generic maps
/// </summary>
public interface IMappingExpression
{
/// <summary>
/// Preserve object identity. Useful for circular references.
/// </summary>
/// <returns></returns>
IMappingExpression PreserveReferences();
/// <summary>
/// Customize configuration for individual constructor parameter
/// </summary>
/// <param name="ctorParamName">Constructor parameter name</param>
/// <param name="paramOptions">Options</param>
/// <returns>Itself</returns>
IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions);
/// <summary>
/// Create a type mapping from the destination to the source type, using the destination members as validation.
/// </summary>
/// <returns>Itself</returns>
IMappingExpression ReverseMap();
/// <summary>
/// Replace the original runtime instance with a new source instance. Useful when ORMs return proxy types with no relationships to runtime types.
/// The returned source object will be mapped instead of what was supplied in the original source object.
/// </summary>
/// <param name="substituteFunc">Substitution function</param>
/// <returns>New source object to map.</returns>
IMappingExpression Substitute(Func<object, object> substituteFunc);
/// <summary>
/// Construct the destination object using the service locator
/// </summary>
/// <returns>Itself</returns>
IMappingExpression ConstructUsingServiceLocator();
/// <summary>
/// For self-referential types, limit recurse depth.
/// Enables PreserveReferences.
/// </summary>
/// <param name="depth">Number of levels to limit to</param>
/// <returns>Itself</returns>
IMappingExpression MaxDepth(int depth);
/// <summary>
/// Supply a custom instantiation expression for the destination type for LINQ projection
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression ConstructProjectionUsing(LambdaExpression ctor);
/// <summary>
/// Supply a custom instantiation function for the destination type, based on the entire resolution context
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object and current resolution context</param>
/// <returns>Itself</returns>
IMappingExpression ConstructUsing(Func<object, ResolutionContext, object> ctor);
/// <summary>
/// Supply a custom instantiation function for the destination type
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression ConstructUsing(Func<object, object> ctor);
/// <summary>
/// Skip member mapping and use a custom expression during LINQ projection
/// </summary>
/// <param name="projectionExpression">Projection expression</param>
void ProjectUsing(Expression<Func<object, object>> projectionExpression);
/// <summary>
/// Customize configuration for all members
/// </summary>
/// <param name="memberOptions">Callback for member options</param>
void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions);
/// <summary>
/// Customize configuration for members not previously configured
/// </summary>
/// <param name="memberOptions">Callback for member options</param>
void ForAllOtherMembers(Action<IMemberConfigurationExpression> memberOptions);
/// <summary>
/// Customize configuration for an individual source member
/// </summary>
/// <param name="sourceMemberName">Source member name</param>
/// <param name="memberOptions">Callback for member configuration options</param>
/// <returns>Itself</returns>
IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions);
/// <summary>
/// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping
/// </summary>
/// <typeparam name="TTypeConverter">Type converter type</typeparam>
void ConvertUsing<TTypeConverter>();
/// <summary>
/// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping
/// Use this method if you need to specify the converter type at runtime
/// </summary>
/// <param name="typeConverterType">Type converter type</param>
void ConvertUsing(Type typeConverterType);
/// <summary>
/// Override the destination type mapping for looking up configuration and instantiation
/// </summary>
/// <param name="typeOverride"></param>
void As(Type typeOverride);
/// <summary>
/// Customize individual members
/// </summary>
/// <param name="name">Name of the member</param>
/// <param name="memberOptions">Callback for configuring member</param>
/// <returns>Itself</returns>
IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions);
/// <summary>
/// Include this configuration in derived types' maps
/// </summary>
/// <param name="derivedSourceType">Derived source type</param>
/// <param name="derivedDestinationType">Derived destination type</param>
/// <returns>Itself</returns>
IMappingExpression Include(Type derivedSourceType, Type derivedDestinationType);
/// <summary>
/// Ignores all destination properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter();
/// <summary>
/// When using ReverseMap, ignores all source properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: destination properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter();
/// <summary>
/// Include the base type map's configuration in this map
/// </summary>
/// <param name="sourceBase">Base source type</param>
/// <param name="destinationBase">Base destination type</param>
/// <returns></returns>
IMappingExpression IncludeBase(Type sourceBase, Type destinationBase);
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression BeforeMap(Action<object, object> beforeFunction);
/// <summary>
/// Execute a custom mapping action before member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression BeforeMap<TMappingAction>()
where TMappingAction : IMappingAction<object, object>;
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression AfterMap(Action<object, object> afterFunction);
/// <summary>
/// Execute a custom mapping action after member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression AfterMap<TMappingAction>()
where TMappingAction : IMappingAction<object, object>;
}
/// <summary>
/// Mapping configuration options
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
public interface IMappingExpression<TSource, TDestination>
{
/// <summary>
/// Customize configuration for a path inside the destination object.
/// </summary>
/// <param name="destinationMember">Expression to the destination subobject</param>
/// <param name="memberOptions">Callback for member options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForPath<TMember>(Expression<Func<TDestination, TMember>> destinationMember,
Action<IPathConfigurationExpression<TSource, TDestination>> memberOptions);
/// <summary>
/// Preserve object identity. Useful for circular references.
/// </summary>
/// <returns></returns>
IMappingExpression<TSource, TDestination> PreserveReferences();
/// <summary>
/// Customize configuration for members not previously configured
/// </summary>
/// <param name="memberOptions">Callback for member options</param>
void ForAllOtherMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions);
/// <summary>
/// Customize configuration for individual member
/// </summary>
/// <param name="destinationMember">Expression to the top-level destination member. This must be a member on the <typeparamref name="TDestination"/>TDestination</param> type
/// <param name="memberOptions">Callback for member options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForMember<TMember>(Expression<Func<TDestination, TMember>> destinationMember,
Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions);
/// <summary>
/// Customize configuration for individual member. Used when the name isn't known at compile-time
/// </summary>
/// <param name="name">Destination member name</param>
/// <param name="memberOptions">Callback for member options</param>
/// <returns></returns>
IMappingExpression<TSource, TDestination> ForMember(string name,
Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions);
/// <summary>
/// Customize configuration for all members
/// </summary>
/// <param name="memberOptions">Callback for member options</param>
void ForAllMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions);
/// <summary>
/// Ignores all <typeparamref name="TDestination"/> properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter();
/// <summary>
/// When using ReverseMap, ignores all <typeparamref name="TSource"/> properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: <typeparamref name="TDestination"/> properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used)
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter();
/// <summary>
/// Include this configuration in derived types' maps
/// </summary>
/// <typeparam name="TOtherSource">Derived source type</typeparam>
/// <typeparam name="TOtherDestination">Derived destination type</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>()
where TOtherSource : TSource
where TOtherDestination : TDestination;
/// <summary>
/// Include the base type map's configuration in this map
/// </summary>
/// <typeparam name="TSourceBase">Base source type</typeparam>
/// <typeparam name="TDestinationBase">Base destination type</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>();
/// <summary>
/// Include this configuration in derived types' maps
/// </summary>
/// <param name="derivedSourceType">Derived source type</param>
/// <param name="derivedDestinationType">Derived destination type</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> Include(Type derivedSourceType, Type derivedDestinationType);
/// <summary>
/// Skip member mapping and use a custom expression during LINQ projection
/// </summary>
/// <param name="projectionExpression">Projection expression</param>
void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression);
/// <summary>
/// Skip member mapping and use a custom function to convert to the destination type
/// </summary>
/// <param name="mappingFunction">Callback to convert from source type to destination type</param>
void ConvertUsing(Func<TSource, TDestination> mappingFunction);
/// <summary>
/// Skip member mapping and use a custom function to convert to the destination type
/// </summary>
/// <param name="mappingFunction">Callback to convert from source type to destination type, including destination object</param>
void ConvertUsing(Func<TSource, TDestination, TDestination> mappingFunction);
/// <summary>
/// Skip member mapping and use a custom function to convert to the destination type
/// </summary>
/// <param name="mappingFunction">Callback to convert from source type to destination type, with source, destination and context</param>
void ConvertUsing(Func<TSource, TDestination, ResolutionContext, TDestination> mappingFunction);
/// <summary>
/// Skip member mapping and use a custom type converter instance to convert to the destination type
/// </summary>
/// <param name="converter">Type converter instance</param>
void ConvertUsing(ITypeConverter<TSource, TDestination> converter);
/// <summary>
/// Skip member mapping and use a custom type converter instance to convert to the destination type
/// </summary>
/// <typeparam name="TTypeConverter">Type converter type</typeparam>
void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>;
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination, ResolutionContext> beforeFunction);
/// <summary>
/// Execute a custom mapping action before member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>()
where TMappingAction : IMappingAction<TSource, TDestination>;
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination, ResolutionContext> afterFunction);
/// <summary>
/// Execute a custom mapping action after member mapping
/// </summary>
/// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>()
where TMappingAction : IMappingAction<TSource, TDestination>;
/// <summary>
/// Supply a custom instantiation function for the destination type
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor);
/// <summary>
/// Supply a custom instantiation expression for the destination type for LINQ projection
/// </summary>
/// <param name="ctor">Callback to create the destination type given the source object</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor);
/// <summary>
/// Supply a custom instantiation function for the destination type, based on the entire resolution context
/// </summary>
/// <param name="ctor">Callback to create the destination type given the current resolution context</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, ResolutionContext, TDestination> ctor);
/// <summary>
/// Override the destination type mapping for looking up configuration and instantiation
/// </summary>
/// <typeparam name="T">Destination type to use</typeparam>
void As<T>() where T : TDestination;
/// <summary>
/// For self-referential types, limit recurse depth.
/// Enables PreserveReferences.
/// </summary>
/// <param name="depth">Number of levels to limit to</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> MaxDepth(int depth);
/// <summary>
/// Construct the destination object using the service locator
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator();
/// <summary>
/// Create a type mapping from the destination to the source type, using the <typeparamref name="TDestination"/> members as validation
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TDestination, TSource> ReverseMap();
/// <summary>
/// Customize configuration for an individual source member
/// </summary>
/// <param name="sourceMember">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param>
/// <param name="memberOptions">Callback for member configuration options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember,
Action<ISourceMemberConfigurationExpression> memberOptions);
/// <summary>
/// Customize configuration for an individual source member. Member name not known until runtime
/// </summary>
/// <param name="sourceMemberName">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param>
/// <param name="memberOptions">Callback for member configuration options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName,
Action<ISourceMemberConfigurationExpression> memberOptions);
/// <summary>
/// Replace the original runtime instance with a new source instance. Useful when ORMs return proxy types with no relationships to runtime types.
/// The returned source object will be mapped instead of what was supplied in the original source object.
/// </summary>
/// <param name="substituteFunc">Substitution function</param>
/// <returns>New source object to map.</returns>
IMappingExpression<TSource, TDestination> Substitute<TSubstitute>(Func<TSource, TSubstitute> substituteFunc);
/// <summary>
/// Customize configuration for individual constructor parameter
/// </summary>
/// <param name="ctorParamName">Constructor parameter name</param>
/// <param name="paramOptions">Options</param>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions);
/// <summary>
/// Disable constructor validation. During mapping this map is used against an existing destination object and never constructed itself.
/// </summary>
/// <returns>Itself</returns>
IMappingExpression<TSource, TDestination> DisableCtorValidation();
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// OrderPreservingPipeliningMergeHelper.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.Linq.Parallel
{
/// <summary>
/// A merge helper that yields results in a streaming fashion, while still ensuring correct output
/// ordering. This merge only works if each producer task generates outputs in the correct order,
/// i.e. with an Increasing (or Correct) order index.
///
/// The merge creates DOP producer tasks, each of which will be writing results into a separate
/// buffer.
///
/// The consumer always waits until each producer buffer contains at least one element. If we don't
/// have one element from each producer, we cannot yield the next element. (If the order index is
/// Correct, or in some special cases with the Increasing order, we could yield sooner. The
/// current algorithm does not take advantage of this.)
///
/// The consumer maintains a producer heap, and uses it to decide which producer should yield the next output
/// result. After yielding an element from a particular producer, the consumer will take another element
/// from the same producer. However, if the producer buffer exceeded a particular threshold, the consumer
/// will take the entire buffer, and give the producer an empty buffer to fill.
///
/// Finally, if the producer notices that its buffer has exceeded an even greater threshold, it will
/// go to sleep and wait until the consumer takes the entire buffer.
/// </summary>
internal class OrderPreservingPipeliningMergeHelper<TOutput, TKey> : IMergeHelper<TOutput>
{
private readonly QueryTaskGroupState _taskGroupState; // State shared among tasks.
private readonly PartitionedStream<TOutput, TKey> _partitions; // Source partitions.
private readonly TaskScheduler _taskScheduler; // The task manager to execute the query.
/// <summary>
/// Whether the producer is allowed to buffer up elements before handing a chunk to the consumer.
/// If false, the producer will make each result available to the consumer immediately after it is
/// produced.
/// </summary>
private readonly bool _autoBuffered;
/// <summary>
/// Buffers for the results. Each buffer has elements added by one producer, and removed
/// by the consumer.
/// </summary>
private readonly Queue<Pair<TKey, TOutput>>[] _buffers;
/// <summary>
/// Whether each producer is done producing. Set to true by individual producers, read by consumer.
/// </summary>
private readonly bool[] _producerDone;
/// <summary>
/// Whether a particular producer is waiting on the consumer. Read by the consumer, set to true
/// by producers, set to false by the consumer.
/// </summary>
private readonly bool[] _producerWaiting;
/// <summary>
/// Whether the consumer is waiting on a particular producer. Read by producers, set to true
/// by consumer, set to false by producer.
/// </summary>
private readonly bool[] _consumerWaiting;
/// <summary>
/// Each object is a lock protecting the corresponding elements in _buffers, _producerDone,
/// _producerWaiting and _consumerWaiting.
/// </summary>
private readonly object[] _bufferLocks;
/// <summary>
/// A comparer used by the producer heap.
/// </summary>
private IComparer<Producer<TKey>> _producerComparer;
/// <summary>
/// The initial capacity of the buffer queue. The value was chosen experimentally.
/// </summary>
internal const int INITIAL_BUFFER_SIZE = 128;
/// <summary>
/// If the consumer notices that the queue reached this limit, it will take the entire buffer from
/// the producer, instead of just popping off one result. The value was chosen experimentally.
/// </summary>
internal const int STEAL_BUFFER_SIZE = 1024;
/// <summary>
/// If the producer notices that the queue reached this limit, it will go to sleep until woken up
/// by the consumer. Chosen experimentally.
/// </summary>
internal const int MAX_BUFFER_SIZE = 8192;
//-----------------------------------------------------------------------------------
// Instantiates a new merge helper.
//
// Arguments:
// partitions - the source partitions from which to consume data.
// ignoreOutput - whether we're enumerating "for effect" or for output.
//
internal OrderPreservingPipeliningMergeHelper(
PartitionedStream<TOutput, TKey> partitions,
TaskScheduler taskScheduler,
CancellationState cancellationState,
bool autoBuffered,
int queryId,
IComparer<TKey> keyComparer)
{
Debug.Assert(partitions != null);
TraceHelpers.TraceInfo("KeyOrderPreservingMergeHelper::.ctor(..): creating an order preserving merge helper");
_taskGroupState = new QueryTaskGroupState(cancellationState, queryId);
_partitions = partitions;
_taskScheduler = taskScheduler;
_autoBuffered = autoBuffered;
int partitionCount = _partitions.PartitionCount;
_buffers = new Queue<Pair<TKey, TOutput>>[partitionCount];
_producerDone = new bool[partitionCount];
_consumerWaiting = new bool[partitionCount];
_producerWaiting = new bool[partitionCount];
_bufferLocks = new object[partitionCount];
if (keyComparer == Util.GetDefaultComparer<int>())
{
Debug.Assert(typeof(TKey) == typeof(int));
_producerComparer = (IComparer<Producer<TKey>>)new ProducerComparerInt();
}
else
{
_producerComparer = new ProducerComparer(keyComparer);
}
}
//-----------------------------------------------------------------------------------
// Schedules execution of the merge itself.
//
void IMergeHelper<TOutput>.Execute()
{
OrderPreservingPipeliningSpoolingTask<TOutput, TKey>.Spool(
_taskGroupState, _partitions, _consumerWaiting, _producerWaiting, _producerDone,
_buffers, _bufferLocks, _taskScheduler, _autoBuffered);
}
//-----------------------------------------------------------------------------------
// Gets the enumerator from which to enumerate output results.
//
IEnumerator<TOutput> IMergeHelper<TOutput>.GetEnumerator()
{
return new OrderedPipeliningMergeEnumerator(this, _producerComparer);
}
//-----------------------------------------------------------------------------------
// Returns the results as an array.
//
public TOutput[] GetResultsAsArray()
{
Debug.Fail("An ordered pipelining merge is not intended to be used this way.");
throw new InvalidOperationException();
}
/// <summary>
/// A comparer used by FixedMaxHeap(Of Producer)
///
/// This comparer will be used by max-heap. We want the producer with the smallest MaxKey to
/// end up in the root of the heap.
///
/// x.MaxKey GREATER_THAN y.MaxKey => x LESS_THAN y => return -
/// x.MaxKey EQUALS y.MaxKey => x EQUALS y => return 0
/// x.MaxKey LESS_THAN y.MaxKey => x GREATER_THAN y => return +
/// </summary>
private class ProducerComparer : IComparer<Producer<TKey>>
{
private IComparer<TKey> _keyComparer;
internal ProducerComparer(IComparer<TKey> keyComparer)
{
_keyComparer = keyComparer;
}
public int Compare(Producer<TKey> x, Producer<TKey> y)
{
return _keyComparer.Compare(y.MaxKey, x.MaxKey);
}
}
/// <summary>
/// Enumerator over the results of an order-preserving pipelining merge.
/// </summary>
private class OrderedPipeliningMergeEnumerator : MergeEnumerator<TOutput>
{
/// <summary>
/// Merge helper associated with this enumerator
/// </summary>
private OrderPreservingPipeliningMergeHelper<TOutput, TKey> _mergeHelper;
/// <summary>
/// Heap used to efficiently locate the producer whose result should be consumed next.
/// For each producer, stores the order index for the next element to be yielded.
///
/// Read and written by the consumer only.
/// </summary>
private readonly FixedMaxHeap<Producer<TKey>> _producerHeap;
/// <summary>
/// Stores the next element to be yielded from each producer. We use a separate array
/// rather than storing this information in the producer heap to keep the Producer struct
/// small.
///
/// Read and written by the consumer only.
/// </summary>
private readonly TOutput[] _producerNextElement;
/// <summary>
/// A private buffer for the consumer. When the size of a producer buffer exceeds a threshold
/// (STEAL_BUFFER_SIZE), the consumer will take ownership of the entire buffer, and give the
/// producer a new empty buffer to place results into.
///
/// Read and written by the consumer only.
/// </summary>
private readonly Queue<Pair<TKey, TOutput>>[] _privateBuffer;
/// <summary>
/// Tracks whether MoveNext() has already been called previously.
/// </summary>
private bool _initialized = false;
/// <summary>
/// Constructor
/// </summary>
internal OrderedPipeliningMergeEnumerator(OrderPreservingPipeliningMergeHelper<TOutput, TKey> mergeHelper, IComparer<Producer<TKey>> producerComparer)
: base(mergeHelper._taskGroupState)
{
int partitionCount = mergeHelper._partitions.PartitionCount;
_mergeHelper = mergeHelper;
_producerHeap = new FixedMaxHeap<Producer<TKey>>(partitionCount, producerComparer);
_privateBuffer = new Queue<Pair<TKey, TOutput>>[partitionCount];
_producerNextElement = new TOutput[partitionCount];
}
/// <summary>
/// Returns the current result
/// </summary>
public override TOutput Current
{
get
{
int producerToYield = _producerHeap.MaxValue.ProducerIndex;
return _producerNextElement[producerToYield];
}
}
/// <summary>
/// Moves the enumerator to the next result, or returns false if there are no more results to yield.
/// </summary>
public override bool MoveNext()
{
if (!_initialized)
{
//
// Initialization: wait until each producer has produced at least one element. Since the order indices
// are increasing, we cannot start yielding until we have at least one element from each producer.
//
_initialized = true;
for (int producer = 0; producer < _mergeHelper._partitions.PartitionCount; producer++)
{
Pair<TKey, TOutput> element = default(Pair<TKey, TOutput>);
// Get the first element from this producer
if (TryWaitForElement(producer, ref element))
{
// Update the producer heap and its helper array with the received element
_producerHeap.Insert(new Producer<TKey>(element.First, producer));
_producerNextElement[producer] = element.Second;
}
else
{
// If this producer didn't produce any results because it encountered an exception,
// cancellation would have been initiated by now. If cancellation has started, we will
// propagate the exception now.
ThrowIfInTearDown();
}
}
}
else
{
// If the producer heap is empty, we are done. In fact, we know that a previous MoveNext() call
// already returned false.
if (_producerHeap.Count == 0)
{
return false;
}
//
// Get the next element from the producer that yielded a value last. Update the producer heap.
// The next producer to yield will be in the front of the producer heap.
//
// The last producer whose result the merge yielded
int lastProducer = _producerHeap.MaxValue.ProducerIndex;
// Get the next element from the same producer
Pair<TKey, TOutput> element = default(Pair<TKey, TOutput>);
if (TryGetPrivateElement(lastProducer, ref element)
|| TryWaitForElement(lastProducer, ref element))
{
// Update the producer heap and its helper array with the received element
_producerHeap.ReplaceMax(new Producer<TKey>(element.First, lastProducer));
_producerNextElement[lastProducer] = element.Second;
}
else
{
// If this producer is done because it encountered an exception, cancellation
// would have been initiated by now. If cancellation has started, we will propagate
// the exception now.
ThrowIfInTearDown();
// This producer is done. Remove it from the producer heap.
_producerHeap.RemoveMax();
}
}
return _producerHeap.Count > 0;
}
/// <summary>
/// If the cancellation of the query has been initiated (because one or more producers
/// encountered exceptions, or because external cancellation token has been set), the method
/// will tear down the query and rethrow the exception.
/// </summary>
private void ThrowIfInTearDown()
{
if (_mergeHelper._taskGroupState.CancellationState.MergedCancellationToken.IsCancellationRequested)
{
try
{
// Wake up all producers. Since the cancellation token has already been
// set, the producers will eventually stop after waking up.
object[] locks = _mergeHelper._bufferLocks;
for (int i = 0; i < locks.Length; i++)
{
lock (locks[i])
{
Monitor.Pulse(locks[i]);
}
}
// Now, we wait for all producers to wake up, notice the cancellation and stop executing.
// QueryEnd will wait on all tasks to complete and then propagate all exceptions.
_taskGroupState.QueryEnd(false);
Debug.Fail("QueryEnd() should have thrown an exception.");
}
finally
{
// Clear the producer heap so that future calls to MoveNext simply return false.
_producerHeap.Clear();
}
}
}
/// <summary>
/// Wait until a producer's buffer is non-empty, or until that producer is done.
/// </summary>
/// <returns>false if there is no element to yield because the producer is done, true otherwise</returns>
private bool TryWaitForElement(int producer, ref Pair<TKey, TOutput> element)
{
Queue<Pair<TKey, TOutput>> buffer = _mergeHelper._buffers[producer];
object bufferLock = _mergeHelper._bufferLocks[producer];
lock (bufferLock)
{
// If the buffer is empty, we need to wait on the producer
if (buffer.Count == 0)
{
// If the producer is already done, return false
if (_mergeHelper._producerDone[producer])
{
element = default(Pair<TKey, TOutput>);
return false;
}
_mergeHelper._consumerWaiting[producer] = true;
Monitor.Wait(bufferLock);
// If the buffer is still empty, the producer is done
if (buffer.Count == 0)
{
Debug.Assert(_mergeHelper._producerDone[producer]);
element = default(Pair<TKey, TOutput>);
return false;
}
}
Debug.Assert(buffer.Count > 0, "Producer's buffer should not be empty here.");
// If the producer is waiting, wake it up
if (_mergeHelper._producerWaiting[producer])
{
Monitor.Pulse(bufferLock);
_mergeHelper._producerWaiting[producer] = false;
}
if (buffer.Count < STEAL_BUFFER_SIZE)
{
element = buffer.Dequeue();
return true;
}
else
{
// Privatize the entire buffer
_privateBuffer[producer] = _mergeHelper._buffers[producer];
// Give an empty buffer to the producer
_mergeHelper._buffers[producer] = new Queue<Pair<TKey, TOutput>>(INITIAL_BUFFER_SIZE);
// No return statement.
// This is the only branch that continues below of the lock region.
}
}
// Get an element out of the private buffer.
bool gotElement = TryGetPrivateElement(producer, ref element);
Debug.Assert(gotElement);
return true;
}
/// <summary>
/// Looks for an element from a particular producer in the consumer's private buffer.
/// </summary>
private bool TryGetPrivateElement(int producer, ref Pair<TKey, TOutput> element)
{
var privateChunk = _privateBuffer[producer];
if (privateChunk != null)
{
if (privateChunk.Count > 0)
{
element = privateChunk.Dequeue();
return true;
}
Debug.Assert(_privateBuffer[producer].Count == 0);
_privateBuffer[producer] = null;
}
return false;
}
public override void Dispose()
{
// Wake up any waiting producers
int partitionCount = _mergeHelper._buffers.Length;
for (int producer = 0; producer < partitionCount; producer++)
{
object bufferLock = _mergeHelper._bufferLocks[producer];
lock (bufferLock)
{
if (_mergeHelper._producerWaiting[producer])
{
Monitor.Pulse(bufferLock);
}
}
}
base.Dispose();
}
}
}
/// <summary>
/// A structure to represent a producer in the producer heap.
/// </summary>
internal struct Producer<TKey>
{
internal readonly TKey MaxKey; // Order index of the next element from this producer
internal readonly int ProducerIndex; // Index of the producer, [0..DOP)
internal Producer(TKey maxKey, int producerIndex)
{
MaxKey = maxKey;
ProducerIndex = producerIndex;
}
}
/// <summary>
/// A comparer used by FixedMaxHeap(Of Producer)
///
/// This comparer will be used by max-heap. We want the producer with the smallest MaxKey to
/// end up in the root of the heap.
///
/// x.MaxKey GREATER_THAN y.MaxKey => x LESS_THAN y => return -
/// x.MaxKey EQUALS y.MaxKey => x EQUALS y => return 0
/// x.MaxKey LESS_THAN y.MaxKey => x GREATER_THAN y => return +
/// </summary>
internal class ProducerComparerInt : IComparer<Producer<int>>
{
public int Compare(Producer<int> x, Producer<int> y)
{
Debug.Assert(x.MaxKey >= 0 && y.MaxKey >= 0); // Guarantees no overflow on next line
return y.MaxKey - x.MaxKey;
}
}
}
| |
/*
* ObjectType.cs - Implementation of the
* "Microsoft.VisualBasic.ObjectType" class.
*
* 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
*/
namespace Microsoft.VisualBasic.CompilerServices
{
using System;
using System.ComponentModel;
using System.Globalization;
#if CONFIG_COMPONENT_MODEL
[EditorBrowsable(EditorBrowsableState.Never)]
#endif
public sealed class ObjectType
{
// Constructor.
public ObjectType() {}
// Get the common type for two objects.
internal static TypeCode CommonType(Object o1, Object o2,
TypeCode tc2, bool compare)
{
TypeCode tc1;
// Get the type codes for the arguments.
if(o1 == null)
{
o1 = o2;
}
else if(o2 == null)
{
o2 = o1;
}
#if !ECMA_COMPAT
if(o1 is IConvertible)
{
tc1 = ((IConvertible)o1).GetTypeCode();
}
else if(o1 is char[])
{
tc1 = TypeCode.String;
}
else
{
tc1 = TypeCode.Empty;
}
if(tc2 == (TypeCode)(-1))
{
if(o2 is IConvertible)
{
tc2 = ((IConvertible)o2).GetTypeCode();
}
else if(o2 is char[])
{
tc2 = TypeCode.String;
}
else
{
tc2 = TypeCode.Empty;
}
}
#else
if(o1 is char[])
{
tc1 = TypeCode.String;
}
else
{
tc1 = GetTypeCode(o1);
}
if(tc2 == (TypeCode)(-1))
{
if(o2 is char[])
{
tc2 = TypeCode.String;
}
else
{
tc2 = GetTypeCode(o2);
}
}
#endif
// Handle the special case of string comparisons.
if(compare)
{
if(tc1 == TypeCode.String || tc2 == TypeCode.String)
{
return TypeCode.String;
}
}
// Determine the common numeric type to use.
switch(tc1)
{
case TypeCode.Boolean:
{
switch(tc2)
{
case TypeCode.Boolean: return TypeCode.Boolean;
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal: return tc2;
case TypeCode.String: return TypeCode.Double;
}
}
break;
case TypeCode.Byte:
{
switch(tc2)
{
case TypeCode.Boolean: return TypeCode.Byte;
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal: return tc2;
case TypeCode.String: return TypeCode.Double;
}
}
break;
case TypeCode.Int16:
{
switch(tc2)
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16: return TypeCode.Int16;
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal: return tc2;
case TypeCode.String: return TypeCode.Double;
}
}
break;
case TypeCode.Int32:
{
switch(tc2)
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32: return TypeCode.Int32;
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal: return tc2;
case TypeCode.String: return TypeCode.Double;
}
}
break;
case TypeCode.Int64:
{
switch(tc2)
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64: return TypeCode.Int64;
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal: return tc2;
case TypeCode.String: return TypeCode.Double;
}
}
break;
case TypeCode.Single:
{
switch(tc2)
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single: return TypeCode.Single;
case TypeCode.Double:
case TypeCode.Decimal: return tc2;
case TypeCode.String: return TypeCode.Double;
}
}
break;
case TypeCode.Double:
case TypeCode.String:
{
switch(tc2)
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.String: return TypeCode.Double;
}
}
break;
case TypeCode.Decimal:
{
switch(tc2)
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Decimal: return TypeCode.Decimal;
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String: return TypeCode.Double;
}
}
break;
}
// We could not determine a common type.
return TypeCode.Empty;
}
private static TypeCode CommonType(Object o1, Object o2, bool compare)
{
return CommonType(o1, o2, (TypeCode)(-1), compare);
}
// Get the common type for two objects, and determine the enum type.
internal static TypeCode CommonType(Object o1, Object o2, out Type enumType)
{
if(o1 is Enum)
{
enumType = o1.GetType();
}
else if(o2 is Enum)
{
enumType = o2.GetType();
}
else
{
enumType = null;
}
return CommonType(o1, o2, (TypeCode)(-1), false);
}
// Get the type code for an object.
internal static TypeCode GetTypeCode(Object obj)
{
#if !ECMA_COMPAT
IConvertible ic = (obj as IConvertible);
if(ic != null)
{
return ic.GetTypeCode();
}
else
{
return TypeCode.Empty;
}
#else
if(obj == null)
{
return TypeCode.Empty;
}
if(obj is Boolean)
{
return TypeCode.Boolean;
}
else if(obj is Char)
{
return TypeCode.Char;
}
else if(obj is SByte)
{
return TypeCode.SByte;
}
else if(obj is Byte)
{
return TypeCode.Byte;
}
else if(obj is Int16)
{
return TypeCode.Int16;
}
else if(obj is UInt16)
{
return TypeCode.UInt16;
}
else if(obj is Int32)
{
return TypeCode.Int32;
}
else if(obj is UInt32)
{
return TypeCode.UInt32;
}
else if(obj is Int64)
{
return TypeCode.Int64;
}
else if(obj is UInt64)
{
return TypeCode.UInt64;
}
else if(obj is Single)
{
return TypeCode.Single;
}
else if(obj is Double)
{
return TypeCode.Double;
}
else if(obj is Decimal)
{
return TypeCode.Decimal;
}
else if(obj is DateTime)
{
return TypeCode.DateTime;
}
else if(obj is String)
{
return TypeCode.String;
}
else
{
return TypeCode.Empty;
}
#endif
}
// Add two objects.
public static Object AddObj(Object o1, Object o2)
{
switch(CommonType(o1, o2, false))
{
case TypeCode.Boolean:
{
return (short)((BooleanType.FromObject(o1) ? -1 : 0) +
(BooleanType.FromObject(o2) ? -1 : 0));
}
// Not reached.
case TypeCode.Byte:
{
int bp = ByteType.FromObject(o1) +
ByteType.FromObject(o2);
if(bp <= 255)
{
return (byte)bp;
}
else if(bp <= 32767)
{
return (short)bp;
}
else
{
return bp;
}
}
// Not reached.
case TypeCode.Int16:
{
int sp = ShortType.FromObject(o1) +
ShortType.FromObject(o2);
if(sp >= -32768 && sp <= 32767)
{
return (short)sp;
}
else
{
return sp;
}
}
// Not reached.
case TypeCode.Int32:
{
int i1 = IntegerType.FromObject(o1);
int i2 = IntegerType.FromObject(o2);
try
{
checked
{
return i1 + i2;
}
}
catch(OverflowException)
{
return ((long)i1) + ((long)i2);
}
}
// Not reached.
case TypeCode.Int64:
{
long l1 = LongType.FromObject(o1);
long l2 = LongType.FromObject(o2);
try
{
checked
{
return l1 + l2;
}
}
catch(OverflowException)
{
try
{
return ((decimal)l1) + ((decimal)l2);
}
catch(OverflowException)
{
return ((double)l1) + ((double)l2);
}
}
}
// Not reached.
case TypeCode.Single:
{
return SingleType.FromObject(o1) +
SingleType.FromObject(o2);
}
// Not reached.
case TypeCode.Double:
case TypeCode.String:
{
return DoubleType.FromObject(o1) +
DoubleType.FromObject(o2);
}
// Not reached.
case TypeCode.Decimal:
{
decimal d1 = DecimalType.FromObject(o1);
decimal d2 = DecimalType.FromObject(o2);
try
{
checked
{
return d1 + d2;
}
}
catch(OverflowException)
{
return ((double)d1) + ((double)d2);
}
}
// Not reached.
}
throw new InvalidCastException(S._("VB_InvalidAddArguments"));
}
// Bitwise AND of two objects.
public static Object BitAndObj(Object o1, Object o2)
{
Type enumType;
Object value;
switch(CommonType(o1, o2, out enumType))
{
case TypeCode.Boolean:
{
return BooleanType.FromObject(o1) &&
BooleanType.FromObject(o2);
}
break;
case TypeCode.Byte:
{
value = (byte)(ByteType.FromObject(o1) &
ByteType.FromObject(o2));
}
break;
case TypeCode.Int16:
{
value = (short)(ShortType.FromObject(o1) &
ShortType.FromObject(o2));
}
break;
case TypeCode.Int32:
{
value = (int)(IntegerType.FromObject(o1) &
IntegerType.FromObject(o2));
}
break;
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
case TypeCode.Decimal:
{
value = (long)(LongType.FromObject(o1) &
LongType.FromObject(o2));
}
break;
default:
{
throw new InvalidCastException
(S._("VB_InvalidBitAndArguments"));
}
// Not reached.
}
if(enumType == null)
{
return value;
}
else
{
return Enum.ToObject(enumType, value);
}
}
// Bitwise OR of two objects.
public static Object BitOrObj(Object o1, Object o2)
{
Type enumType;
Object value;
switch(CommonType(o1, o2, out enumType))
{
case TypeCode.Boolean:
{
return BooleanType.FromObject(o1) ||
BooleanType.FromObject(o2);
}
break;
case TypeCode.Byte:
{
value = (byte)(ByteType.FromObject(o1) |
ByteType.FromObject(o2));
}
break;
case TypeCode.Int16:
{
value = (short)(ShortType.FromObject(o1) |
ShortType.FromObject(o2));
}
break;
case TypeCode.Int32:
{
value = (int)(IntegerType.FromObject(o1) |
IntegerType.FromObject(o2));
}
break;
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
case TypeCode.Decimal:
{
value = (long)(LongType.FromObject(o1) |
LongType.FromObject(o2));
}
break;
default:
{
throw new InvalidCastException
(S._("VB_InvalidBitOrArguments"));
}
// Not reached.
}
if(enumType == null)
{
return value;
}
else
{
return Enum.ToObject(enumType, value);
}
}
// Bitwise XOR of two objects.
public static Object BitXorObj(Object o1, Object o2)
{
Type enumType;
Object value;
switch(CommonType(o1, o2, out enumType))
{
case TypeCode.Boolean:
{
return (((BooleanType.FromObject(o1) ? -1 : 0) ^
(BooleanType.FromObject(o2) ? -1 : 0)) != 0);
}
break;
case TypeCode.Byte:
{
value = (byte)(ByteType.FromObject(o1) ^
ByteType.FromObject(o2));
}
break;
case TypeCode.Int16:
{
value = (short)(ShortType.FromObject(o1) ^
ShortType.FromObject(o2));
}
break;
case TypeCode.Int32:
{
value = (int)(IntegerType.FromObject(o1) ^
IntegerType.FromObject(o2));
}
break;
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
case TypeCode.Decimal:
{
value = (long)(LongType.FromObject(o1) ^
LongType.FromObject(o2));
}
break;
default:
{
throw new InvalidCastException
(S._("VB_InvalidBitXorArguments"));
}
// Not reached.
}
if(enumType == null)
{
return value;
}
else
{
return Enum.ToObject(enumType, value);
}
}
// Divide two objects.
public static Object DivObj(Object o1, Object o2)
{
switch(CommonType(o1, o2, false))
{
case TypeCode.Boolean:
{
return (BooleanType.FromObject(o1) ? -1.0 : 0.0) *
(BooleanType.FromObject(o2) ? -1.0 : 0.0);
}
// Not reached.
case TypeCode.Single:
{
return SingleType.FromObject(o1) /
SingleType.FromObject(o2);
}
// Not reached.
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.String:
{
return DoubleType.FromObject(o1) /
DoubleType.FromObject(o2);
}
// Not reached.
case TypeCode.Decimal:
{
decimal d1 = DecimalType.FromObject(o1);
decimal d2 = DecimalType.FromObject(o2);
try
{
checked
{
return d1 / d2;
}
}
catch(OverflowException)
{
return ((float)d1) / ((float)d2);
}
}
// Not reached.
}
throw new InvalidCastException(S._("VB_InvalidDivArguments"));
}
// Convert an object into its primitive form.
public static Object GetObjectValuePrimitive(Object o)
{
#if !ECMA_COMPAT
if(o == null)
{
return null;
}
switch(GetTypeCode(o))
{
case TypeCode.Boolean:
return ((IConvertible)o).ToBoolean(null);
case TypeCode.Char:
return ((IConvertible)o).ToChar(null);
case TypeCode.Byte:
return ((IConvertible)o).ToByte(null);
case TypeCode.SByte:
return ((IConvertible)o).ToSByte(null);
case TypeCode.Int16:
return ((IConvertible)o).ToInt16(null);
case TypeCode.UInt16:
return ((IConvertible)o).ToUInt16(null);
case TypeCode.Int32:
return ((IConvertible)o).ToInt32(null);
case TypeCode.UInt32:
return ((IConvertible)o).ToUInt32(null);
case TypeCode.Int64:
return ((IConvertible)o).ToInt64(null);
case TypeCode.UInt64:
return ((IConvertible)o).ToUInt64(null);
case TypeCode.Single:
return ((IConvertible)o).ToSingle(null);
case TypeCode.Double:
return ((IConvertible)o).ToDouble(null);
case TypeCode.Decimal:
return ((IConvertible)o).ToDecimal(null);
case TypeCode.String:
return ((IConvertible)o).ToString(null);
case TypeCode.DateTime:
return ((IConvertible)o).ToDateTime(null);
}
#endif // !ECMA_COMPAT
return o;
}
// Integer divide two objects.
public static Object IDivObj(Object o1, Object o2)
{
switch(CommonType(o1, o2, false))
{
case TypeCode.Boolean:
{
return (short)((BooleanType.FromObject(o1) ? -1 : 0) /
(BooleanType.FromObject(o2) ? -1 : 0));
}
// Not reached.
case TypeCode.Byte:
{
return (byte)(ByteType.FromObject(o1) /
ByteType.FromObject(o2));
}
// Not reached.
case TypeCode.Int16:
{
return (short)(ShortType.FromObject(o1) /
ShortType.FromObject(o2));
}
// Not reached.
case TypeCode.Int32:
{
return (int)(IntegerType.FromObject(o1) /
IntegerType.FromObject(o2));
}
// Not reached.
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
case TypeCode.Decimal:
{
return (long)(LongType.FromObject(o1) /
LongType.FromObject(o2));
}
// Not reached.
}
throw new InvalidCastException(S._("VB_InvalidIDivArguments"));
}
// Determine if two objects are alike.
public static bool LikeObj(Object vLeft, Object vRight,
CompareMethod CompareOption)
{
return StringType.StrLike(StringType.FromObject(vLeft),
StringType.FromObject(vRight),
CompareOption);
}
// Modulus two objects.
public static Object ModObj(Object o1, Object o2)
{
switch(CommonType(o1, o2, false))
{
case TypeCode.Boolean:
{
return (short)((BooleanType.FromObject(o1) ? -1 : 0) %
(BooleanType.FromObject(o2) ? -1 : 0));
}
// Not reached.
case TypeCode.Byte:
{
return (byte)(ByteType.FromObject(o1) %
ByteType.FromObject(o2));
}
// Not reached.
case TypeCode.Int16:
{
return (short)(ShortType.FromObject(o1) %
ShortType.FromObject(o2));
}
// Not reached.
case TypeCode.Int32:
{
return IntegerType.FromObject(o1) %
IntegerType.FromObject(o2);
}
// Not reached.
case TypeCode.Int64:
{
return LongType.FromObject(o1) %
LongType.FromObject(o2);
}
// Not reached.
case TypeCode.Single:
{
return SingleType.FromObject(o1) %
SingleType.FromObject(o2);
}
// Not reached.
case TypeCode.Double:
case TypeCode.String:
{
return DoubleType.FromObject(o1) %
DoubleType.FromObject(o2);
}
// Not reached.
case TypeCode.Decimal:
{
return DecimalType.FromObject(o1) %
DecimalType.FromObject(o2);
}
// Not reached.
}
throw new InvalidCastException(S._("VB_InvalidModArguments"));
}
// Multiply two objects.
public static Object MulObj(Object o1, Object o2)
{
switch(CommonType(o1, o2, false))
{
case TypeCode.Boolean:
{
return (short)((BooleanType.FromObject(o1) ? -1 : 0) *
(BooleanType.FromObject(o2) ? -1 : 0));
}
// Not reached.
case TypeCode.Byte:
{
int bp = ByteType.FromObject(o1) *
ByteType.FromObject(o2);
if(bp <= 255)
{
return (byte)bp;
}
else if(bp <= 32767)
{
return (short)bp;
}
else
{
return bp;
}
}
// Not reached.
case TypeCode.Int16:
{
int sp = ShortType.FromObject(o1) *
ShortType.FromObject(o2);
if(sp >= -32768 && sp <= 32767)
{
return (short)sp;
}
else
{
return sp;
}
}
// Not reached.
case TypeCode.Int32:
{
int i1 = IntegerType.FromObject(o1);
int i2 = IntegerType.FromObject(o2);
try
{
checked
{
return i1 * i2;
}
}
catch(OverflowException)
{
return ((long)i1) * ((long)i2);
}
}
// Not reached.
case TypeCode.Int64:
{
long l1 = LongType.FromObject(o1);
long l2 = LongType.FromObject(o2);
try
{
checked
{
return l1 * l2;
}
}
catch(OverflowException)
{
try
{
return ((decimal)l1) * ((decimal)l2);
}
catch(OverflowException)
{
return ((double)l1) * ((double)l2);
}
}
}
// Not reached.
case TypeCode.Single:
{
return SingleType.FromObject(o1) *
SingleType.FromObject(o2);
}
// Not reached.
case TypeCode.Double:
case TypeCode.String:
{
return DoubleType.FromObject(o1) *
DoubleType.FromObject(o2);
}
// Not reached.
case TypeCode.Decimal:
{
decimal d1 = DecimalType.FromObject(o1);
decimal d2 = DecimalType.FromObject(o2);
try
{
checked
{
return d1 * d2;
}
}
catch(OverflowException)
{
return ((double)d1) * ((double)d2);
}
}
// Not reached.
}
throw new InvalidCastException(S._("VB_InvalidMulArguments"));
}
// Negate an object.
public static Object NegObj(Object o)
{
if(o == null)
{
return 0;
}
switch(GetTypeCode(o))
{
case TypeCode.Boolean:
return (short)(BooleanType.FromObject(o) ? 1 : 0);
case TypeCode.Byte:
return (short)(-(ByteType.FromObject(o)));
case TypeCode.Int16:
{
int svalue = -(ShortType.FromObject(o));
if(svalue >= -32768 && svalue <= 32767)
{
return (short)svalue;
}
else
{
return svalue;
}
}
// Not reached.
case TypeCode.Int32:
{
int ivalue = IntegerType.FromObject(o);
if(ivalue != Int32.MinValue)
{
return -ivalue;
}
else
{
return -((long)ivalue);
}
}
// Not reached.
case TypeCode.Int64:
{
long lvalue = LongType.FromObject(o);
if(lvalue != Int64.MinValue)
{
return -lvalue;
}
else
{
return -((decimal)lvalue);
}
}
// Not reached.
case TypeCode.Single:
return -(SingleType.FromObject(o));
case TypeCode.Double:
case TypeCode.String:
return -(DoubleType.FromObject(o));
case TypeCode.Decimal:
return -(DecimalType.FromObject(o));
}
throw new InvalidCastException(S._("VB_InvalidNegArgument"));
}
// Bitwise NOT an object.
public static Object NotObj(Object o)
{
Type enumType;
Object value;
switch(CommonType(o, o, out enumType))
{
case TypeCode.Boolean:
{
return !BooleanType.FromObject(o);
}
break;
case TypeCode.Byte:
{
value = (byte)(~(ByteType.FromObject(o)));
}
break;
case TypeCode.Int16:
{
value = (short)(~(ShortType.FromObject(o)));
}
break;
case TypeCode.Int32:
{
value = ~(IntegerType.FromObject(o));
}
break;
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
case TypeCode.Decimal:
{
value = ~(LongType.FromObject(o));
}
break;
default:
{
throw new InvalidCastException
(S._("VB_InvalidNotArgument"));
}
// Not reached.
}
if(enumType == null)
{
return value;
}
else
{
return Enum.ToObject(enumType, value);
}
}
// Test two objects and return -1, 0, or 1.
public static int ObjTst(Object o1, Object o2, bool TextCompare)
{
switch(CommonType(o1, o2, true))
{
case TypeCode.Boolean:
{
int b1 = (BooleanType.FromObject(o1) ? -1 : 0);
int b2 = (BooleanType.FromObject(o2) ? -1 : 0);
if(b1 < b2)
{
return -1;
}
else if(b1 > b2)
{
return 1;
}
else
{
return 0;
}
}
// Not reached.
case TypeCode.Byte:
{
byte by1 = ByteType.FromObject(o1);
byte by2 = ByteType.FromObject(o2);
if(by1 < by2)
{
return -1;
}
else if(by1 > by2)
{
return 1;
}
else
{
return 0;
}
}
// Not reached.
case TypeCode.Int16:
{
short s1 = ShortType.FromObject(o1);
short s2 = ShortType.FromObject(o2);
if(s1 < s2)
{
return -1;
}
else if(s1 > s2)
{
return 1;
}
else
{
return 0;
}
}
// Not reached.
case TypeCode.Int32:
{
int i1 = IntegerType.FromObject(o1);
int i2 = IntegerType.FromObject(o2);
if(i1 < i2)
{
return -1;
}
else if(i1 > i2)
{
return 1;
}
else
{
return 0;
}
}
// Not reached.
case TypeCode.Int64:
{
long l1 = LongType.FromObject(o1);
long l2 = LongType.FromObject(o2);
if(l1 < l2)
{
return -1;
}
else if(l1 > l2)
{
return 1;
}
else
{
return 0;
}
}
// Not reached.
case TypeCode.Single:
{
float f1 = SingleType.FromObject(o1);
float f2 = SingleType.FromObject(o2);
if(f1 < f2)
{
return -1;
}
else if(f1 > f2)
{
return 1;
}
else
{
return 0;
}
}
// Not reached.
case TypeCode.Double:
{
double d1 = DoubleType.FromObject(o1);
double d2 = DoubleType.FromObject(o2);
if(d1 < d2)
{
return -1;
}
else if(d1 > d2)
{
return 1;
}
else
{
return 0;
}
}
// Not reached.
case TypeCode.String:
{
if(!TextCompare)
{
return String.CompareOrdinal
(StringType.FromObject(o1),
StringType.FromObject(o2));
}
else
{
return CultureInfo.CurrentCulture.CompareInfo
.Compare(StringType.FromObject(o1),
StringType.FromObject(o2),
CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreWidth);
}
}
// Not reached.
case TypeCode.Decimal:
{
decimal D1 = DecimalType.FromObject(o1);
decimal D2 = DecimalType.FromObject(o2);
if(D1 < D2)
{
return -1;
}
else if(D1 > D2)
{
return 1;
}
else
{
return 0;
}
}
// Not reached.
}
throw new InvalidCastException(S._("VB_InvalidTstArguments"));
}
// Unary plus an object.
public static Object PlusObj(Object o)
{
if(o == null)
{
return 0;
}
switch(GetTypeCode(o))
{
case TypeCode.Boolean:
return (short)(BooleanType.FromObject(o) ? -1 : 0);
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.String:
return DoubleType.FromObject(o);
}
throw new InvalidCastException(S._("VB_InvalidPlusArgument"));
}
// Power two objects.
public static Object PowObj(Object o1, Object o2)
{
switch(CommonType(o1, o2, false))
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
case TypeCode.Decimal:
{
return Math.Pow(DoubleType.FromObject(o1),
DoubleType.FromObject(o2));
}
// Not reached.
}
throw new InvalidCastException(S._("VB_InvalidPowArguments"));
}
// Shift an object left by an amount.
public static Object ShiftLeftObj(Object o1, int amount)
{
switch(GetTypeCode(o1))
{
case TypeCode.Boolean:
{
return (short)((BooleanType.FromObject(o1) ? -1 : 0) <<
(amount & 0x0F));
}
// Not reached.
case TypeCode.Byte:
{
return (byte)(ByteType.FromObject(o1) <<
(amount & 0x07));
}
// Not reached.
case TypeCode.Int16:
{
return (short)(ShortType.FromObject(o1) <<
(amount & 0x0F));
}
// Not reached.
case TypeCode.Int32:
{
return (int)(IntegerType.FromObject(o1) <<
(amount & 0x1F));
}
// Not reached.
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
case TypeCode.Decimal:
{
return (long)(LongType.FromObject(o1) <<
(amount & 0x3F));
}
// Not reached.
}
throw new InvalidCastException
(S._("VB_InvalidShiftLeftArguments"));
}
// Shift an object right by an amount.
public static Object ShiftRightObj(Object o1, int amount)
{
switch(GetTypeCode(o1))
{
case TypeCode.Boolean:
{
return (short)((BooleanType.FromObject(o1) ? -1 : 0) >>
(amount & 0x0F));
}
// Not reached.
case TypeCode.Byte:
{
return (byte)(ByteType.FromObject(o1) >>
(amount & 0x07));
}
// Not reached.
case TypeCode.Int16:
{
return (short)(ShortType.FromObject(o1) >>
(amount & 0x0F));
}
// Not reached.
case TypeCode.Int32:
{
return (int)(IntegerType.FromObject(o1) >>
(amount & 0x1F));
}
// Not reached.
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
case TypeCode.Decimal:
{
return (long)(LongType.FromObject(o1) >>
(amount & 0x3F));
}
// Not reached.
}
throw new InvalidCastException
(S._("VB_InvalidShiftRightArguments"));
}
// Concatenate two objects.
public static Object StrCatObj(Object o1, Object o2)
{
#if !ECMA_COMPAT
if(o1 is DBNull)
{
o1 = String.Empty;
}
if(o2 is DBNull)
{
o2 = String.Empty;
}
#endif
return StringType.FromObject(o1) + StringType.FromObject(o2);
}
// Subtract two objects.
public static Object SubObj(Object o1, Object o2)
{
switch(CommonType(o1, o2, false))
{
case TypeCode.Boolean:
{
return (short)((BooleanType.FromObject(o1) ? -1 : 0) -
(BooleanType.FromObject(o2) ? -1 : 0));
}
// Not reached.
case TypeCode.Byte:
{
int bp = ByteType.FromObject(o1) -
ByteType.FromObject(o2);
if(bp <= 255)
{
return (byte)bp;
}
else if(bp <= 32767)
{
return (short)bp;
}
else
{
return bp;
}
}
// Not reached.
case TypeCode.Int16:
{
int sp = ShortType.FromObject(o1) -
ShortType.FromObject(o2);
if(sp >= -32768 && sp <= 32767)
{
return (short)sp;
}
else
{
return sp;
}
}
// Not reached.
case TypeCode.Int32:
{
int i1 = IntegerType.FromObject(o1);
int i2 = IntegerType.FromObject(o2);
try
{
checked
{
return i1 - i2;
}
}
catch(OverflowException)
{
return ((long)i1) - ((long)i2);
}
}
// Not reached.
case TypeCode.Int64:
{
long l1 = LongType.FromObject(o1);
long l2 = LongType.FromObject(o2);
try
{
checked
{
return l1 - l2;
}
}
catch(OverflowException)
{
try
{
return ((decimal)l1) - ((decimal)l2);
}
catch(OverflowException)
{
return ((double)l1) - ((double)l2);
}
}
}
// Not reached.
case TypeCode.Single:
{
return SingleType.FromObject(o1) -
SingleType.FromObject(o2);
}
// Not reached.
case TypeCode.Double:
case TypeCode.String:
{
return DoubleType.FromObject(o1) -
DoubleType.FromObject(o2);
}
// Not reached.
case TypeCode.Decimal:
{
decimal d1 = DecimalType.FromObject(o1);
decimal d2 = DecimalType.FromObject(o2);
try
{
checked
{
return d1 - d2;
}
}
catch(OverflowException)
{
return ((double)d1) - ((double)d2);
}
}
// Not reached.
}
throw new InvalidCastException(S._("VB_InvalidSubArguments"));
}
// XOR two objects as boolean values.
public static Object XorObj(Object o1, Object o2)
{
if(o1 == null && o2 == null)
{
return false;
}
switch(CommonType(o1, o2, false))
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.String:
case TypeCode.Decimal:
{
bool b1 = BooleanType.FromObject(o1);
bool b2 = BooleanType.FromObject(o2);
return ((b1 && !b2) || (!b1 && b2));
}
// Not reached.
}
throw new InvalidCastException(S._("VB_InvalidXorArguments"));
}
}; // class ObjectType
}; // namespace Microsoft.VisualBasic.CompilerServices
| |
// 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 ShiftRightLogical128BitLaneSByte1()
{
var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneSByte1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.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 (Sse2.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__ShiftRightLogical128BitLaneSByte1
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(SByte);
private const int RetElementCount = VectorSize / sizeof(SByte);
private static SByte[] _data = new SByte[Op1ElementCount];
private static Vector128<SByte> _clsVar;
private Vector128<SByte> _fld;
private SimpleUnaryOpTest__DataTable<SByte, SByte> _dataTable;
static SimpleUnaryOpTest__ShiftRightLogical128BitLaneSByte1()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightLogical128BitLaneSByte1()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)8; }
_dataTable = new SimpleUnaryOpTest__DataTable<SByte, SByte>(_data, new SByte[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.ShiftRightLogical128BitLane(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.ShiftRightLogical128BitLane(
Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.ShiftRightLogical128BitLane(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.ShiftRightLogical128BitLane(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneSByte1();
var result = Sse2.ShiftRightLogical128BitLane(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.ShiftRightLogical128BitLane(_fld, 1);
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<SByte> firstOp, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "")
{
if (result[0] != 8)
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((i == 15 ? result[i] != 0 : result[i] != 8))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical128BitLane)}<SByte>(Vector128<SByte><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using Emgu.CV.Structure;
using Color = Microsoft.Xna.Framework.Color;
using Size = System.Drawing.Size;
using Emgu.CV;
using Emgu.CV.CvEnum;
namespace Pentacorn.Captures
{
class CLEyeCapture : Capture
{
public static IList<Capture> Devices { get; private set; }
public Color WhiteBalance
{
get
{
return new Color(CLEyeGetCameraParameter(Handle, Param.CLEYE_WHITEBALANCE_RED_0_255),
CLEyeGetCameraParameter(Handle, Param.CLEYE_WHITEBALANCE_BLUE_0_255),
CLEyeGetCameraParameter(Handle, Param.CLEYE_WHITEBALANCE_GREEN_0_255));
}
private set
{
CLEyeSetCameraParameter(Handle, Param.CLEYE_WHITEBALANCE_RED_0_255, value.R);
CLEyeSetCameraParameter(Handle, Param.CLEYE_WHITEBALANCE_BLUE_0_255, value.G);
CLEyeSetCameraParameter(Handle, Param.CLEYE_WHITEBALANCE_GREEN_0_255, value.B);
}
}
public int Gain
{
get { return CLEyeGetCameraParameter(Handle, Param.CLEYE_GAIN_0_79); }
private set { CLEyeSetCameraParameter(Handle, Param.CLEYE_GAIN_0_79, value); }
}
public override TimeSpan Exposure
{
// Taken from the CLEye forums...
//
// Exposure depends on the capture resolution. Assuming that you are capturing at 640x480 the exposure is as following:
//
// Texposure = ExposureValue * Trow
//
// There are total of 510 rows between two VSync periods. So for example if you are capturing at 30fps this time amounts to:
//
// Trow = (1/30) / 510 = 6.5359e-5 s
//
// So for your desired exposure time of 1/250, the ExposureValue would be:
//
// ExposureValue = (1/250) / Trow = 61.2 ~ 61
//
// Therefore if you capture at 30fps at 640x480 resolution, in order to get
// exposure time of 1/250 s you would set the sensor exposure parameter value ExposureValue=61.
//
// The thing to remember is that at:
// 1. 640x480 there are total of 510*Trow between two consecutive Vsync periods.
// 2. 320x480 there are total of 278*Trow between two consecutive Vsync periods.
get
{
var ev = CLEyeGetCameraParameter(Handle, Param.CLEYE_EXPOSURE_0_511);
return TimeSpan.FromSeconds(ev * ExpTeeRow);
}
set
{
var ev = value.TotalSeconds / ExpTeeRow;
CLEyeSetCameraParameter(Handle, Param.CLEYE_EXPOSURE_0_511, (int)ev.Clamp(0, 511));
}
}
private int ExpRows { get { return Resolution == ResolutionMode.CLEYE_QVGA ? 278 : 510; } }
private double ExpTeeRow { get { return (1.0 / FPS) / ExpRows; } }
public override void Close()
{
Running = false;
if (Thread.IsAlive)
Thread.Join();
}
private static Size ResolutionToSize(ResolutionMode rm) { return rm == ResolutionMode.CLEYE_QVGA ? new Size(320, 240) : new Size(640, 480); }
private CLEyeCapture(Guid guid)
: base("CLEye Camera", guid.ToString(), ResolutionToSize(Resolution))
{
Handle = CLEyeCreateCamera(guid, Mode, Resolution, FPS);
if (Handle == IntPtr.Zero)
throw new Exception("Unable to obtain Handle to CLEye camera device.");
int w = 0, h = 0;
CLEyeCameraGetFrameDimensions(Handle, ref w, ref h);
Thread = new Thread(this.Runner);
Thread.IsBackground = true;
Thread.Start();
}
private void Runner()
{
Exposure = TimeSpan.FromSeconds(0.9 / FPS);
WhiteBalance = Color.White;
Gain = 0;
CLEyeSetCameraParameter(Handle, Param.CLEYE_AUTO_EXPOSURE_0_1, 0);
CLEyeSetCameraParameter(Handle, Param.CLEYE_AUTO_GAIN_0_1, 0);
CLEyeSetCameraParameter(Handle, Param.CLEYE_AUTO_WHITEBALANCE_0_1, 0);
if (Global.No)
{
CLEyeSetCameraParameter(Handle, Param.CLEYE_AUTO_WHITEBALANCE_0_1, 1);
CLEyeSetCameraParameter(Handle, Param.CLEYE_AUTO_GAIN_0_1, 1);
CLEyeSetCameraParameter(Handle, Param.CLEYE_AUTO_EXPOSURE_0_1, 1);
}
CLEyeCameraStart(Handle);
while (Running)
{
using (var rgba = new Picture<Rgba, byte>(this.Width, this.Height))
using (var gray = new Picture<Gray, byte>(this.Width, this.Height))
using (var bayer = new Picture<Gray, byte>(this.Width, this.Height))
using (var bgr = new Picture<Bgr, byte>(this.Width, this.Height))
{
var waitTimeOutMs = 2000;
var ok = NumChannels == 1
? CLEyeCameraGetFrame(Handle, bayer.Ptr, waitTimeOutMs)
: false;
if (!ok)
bayer.Errorize();
CvInvoke.cvCvtColor(bayer.Emgu.Ptr, bgr.Emgu.Ptr, COLOR_CONVERSION.CV_BayerGB2BGR_VNG);
CvInvoke.cvCvtColor(bgr.Emgu.Ptr, rgba.Emgu.Ptr, COLOR_CONVERSION.CV_BGR2RGBA);
CvInvoke.cvCvtColor(bgr.Emgu.Ptr, gray.Emgu.Ptr, COLOR_CONVERSION.CV_BGR2GRAY);
OnNext(gray.AddRef(), rgba.AddRef());
}
}
if (Handle != IntPtr.Zero)
{
CLEyeCameraStop(Handle);
CLEyeDestroyCamera(Handle);
Handle = IntPtr.Zero;
}
}
private enum ColorMode
{
CLEYE_MONO_PROCESSED,
CLEYE_COLOR_PROCESSED,
CLEYE_MONO_RAW,
CLEYE_COLOR_RAW,
CLEYE_BAYER_RAW
};
private enum ResolutionMode
{
CLEYE_QVGA,
CLEYE_VGA
};
private enum Param
{
CLEYE_AUTO_GAIN_0_1,
CLEYE_GAIN_0_79,
CLEYE_AUTO_EXPOSURE_0_1,
CLEYE_EXPOSURE_0_511,
CLEYE_AUTO_WHITEBALANCE_0_1,
CLEYE_WHITEBALANCE_RED_0_255,
CLEYE_WHITEBALANCE_GREEN_0_255,
CLEYE_WHITEBALANCE_BLUE_0_255,
CLEYE_HFLIP_0_1,
CLEYE_VFLIP_0_1,
CLEYE_HKEYSTONE_PLUS_MINUS_500,
CLEYE_VKEYSTONE_PLUS_MINUS_500,
CLEYE_XOFFSET_PLUS_MINUS_500,
CLEYE_YOFFSET_PLUS_MINUS_500,
CLEYE_ROTATION_PLUS_MINUS_500,
CLEYE_ZOOM_PLUS_MINUS_500,
CLEYE_LENSCORRECTION1_PLUS_MINUS_500,
CLEYE_LENSCORRECTION2_PLUS_MINUS_500,
CLEYE_LENSCORRECTION3_PLUS_MINUS_500,
CLEYE_LENSBRIGHTNESS_PLUS_MINUS_500
};
[DllImport("CLEyeMulticam.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int CLEyeGetCameraCount();
[DllImport("CLEyeMulticam.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern Guid CLEyeGetCameraUUID(int camId);
[DllImport("CLEyeMulticam.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr CLEyeCreateCamera(Guid camUUID, ColorMode mode, ResolutionMode res, float frameRate);
[DllImport("CLEyeMulticam.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool CLEyeDestroyCamera(IntPtr camera);
[DllImport("CLEyeMulticam.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool CLEyeCameraStart(IntPtr camera);
[DllImport("CLEyeMulticam.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool CLEyeCameraStop(IntPtr camera);
[DllImport("CLEyeMulticam.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool CLEyeCameraLED(IntPtr camera, bool on);
[DllImport("CLEyeMulticam.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool CLEyeSetCameraParameter(IntPtr camera, Param param, int value);
[DllImport("CLEyeMulticam.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int CLEyeGetCameraParameter(IntPtr camera, Param param);
[DllImport("CLEyeMulticam.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool CLEyeCameraGetFrameDimensions(IntPtr camera, ref int width, ref int height);
[DllImport("CLEyeMulticam.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool CLEyeCameraGetFrame(IntPtr camera, IntPtr pData, int waitTimeout);
static CLEyeCapture()
{
var count = CLEyeGetCameraCount();
Devices = new CLEyeCapture[count];
for (int i = 0; i < count; ++i)
Devices[i] = new CLEyeCapture(CLEyeGetCameraUUID(i));
}
private readonly int FPS = 30;
private const int NumChannels = (Mode == ColorMode.CLEYE_COLOR_PROCESSED || Mode == ColorMode.CLEYE_COLOR_RAW) ? 4 : 1;
private const ColorMode Mode = ColorMode.CLEYE_BAYER_RAW;
private const ResolutionMode Resolution = ResolutionMode.CLEYE_VGA;
private IntPtr Handle;
private Thread Thread;
private volatile bool Running = true;
}
}
| |
// ZlibBaseStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-August-06 21:22:38>
//
// ------------------------------------------------------------------
//
// This module defines the ZlibBaseStream class, which is an intnernal
// base class for DeflateStream, ZlibStream and GZipStream.
//
// ------------------------------------------------------------------
using System;
using System.IO;
namespace Ionic.Zlib
{
internal enum ZlibStreamFlavor { ZLIB = 1950, DEFLATE = 1951, GZIP = 1952 }
internal class ZlibBaseStream : System.IO.Stream
{
protected internal ZlibCodec _z = null; // deferred init... new ZlibCodec();
protected internal StreamMode _streamMode = StreamMode.Undefined;
protected internal FlushType _flushMode;
protected internal ZlibStreamFlavor _flavor;
protected internal CompressionMode _compressionMode;
protected internal CompressionLevel _level;
protected internal bool _leaveOpen;
protected internal byte[] _workingBuffer;
protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault;
protected internal byte[] _buf1 = new byte[1];
protected internal System.IO.Stream _stream;
protected internal CompressionStrategy Strategy = CompressionStrategy.Default;
// workitem 7159
Ionic.Crc.CRC32 crc;
protected internal string _GzipFileName;
protected internal string _GzipComment;
protected internal DateTime _GzipMtime;
protected internal int _gzipHeaderByteCount;
internal int Crc32 { get { if (crc == null) return 0; return crc.Crc32Result; } }
public ZlibBaseStream(System.IO.Stream stream,
CompressionMode compressionMode,
CompressionLevel level,
ZlibStreamFlavor flavor,
bool leaveOpen)
: base()
{
this._flushMode = FlushType.None;
//this._workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT];
this._stream = stream;
this._leaveOpen = leaveOpen;
this._compressionMode = compressionMode;
this._flavor = flavor;
this._level = level;
// workitem 7159
if (flavor == ZlibStreamFlavor.GZIP)
{
this.crc = new Ionic.Crc.CRC32();
}
}
protected internal bool _wantCompress
{
get
{
return (this._compressionMode == CompressionMode.Compress);
}
}
private ZlibCodec z
{
get
{
if (_z == null)
{
bool wantRfc1950Header = (this._flavor == ZlibStreamFlavor.ZLIB);
_z = new ZlibCodec();
if (this._compressionMode == CompressionMode.Decompress)
{
_z.InitializeInflate(wantRfc1950Header);
}
else
{
_z.Strategy = Strategy;
_z.InitializeDeflate(this._level, wantRfc1950Header);
}
}
return _z;
}
}
private byte[] workingBuffer
{
get
{
if (_workingBuffer == null)
_workingBuffer = new byte[_bufferSize];
return _workingBuffer;
}
}
public override void Write(System.Byte[] buffer, int offset, int count)
{
// workitem 7159
// calculate the CRC on the unccompressed data (before writing)
if (crc != null)
crc.SlurpBlock(buffer, offset, count);
if (_streamMode == StreamMode.Undefined)
_streamMode = StreamMode.Writer;
else if (_streamMode != StreamMode.Writer)
throw new ZlibException("Cannot Write after Reading.");
if (count == 0)
return;
// first reference of z property will initialize the private var _z
z.InputBuffer = buffer;
_z.NextIn = offset;
_z.AvailableBytesIn = count;
bool done = false;
do
{
_z.OutputBuffer = workingBuffer;
_z.NextOut = 0;
_z.AvailableBytesOut = _workingBuffer.Length;
int rc = (_wantCompress)
? _z.Deflate(_flushMode)
: _z.Inflate(_flushMode);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message);
//if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
_stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;
// If GZIP and de-compress, we're done when 8 bytes remain.
if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress)
done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0);
}
while (!done);
}
private void finish()
{
if (_z == null) return;
if (_streamMode == StreamMode.Writer)
{
bool done = false;
do
{
_z.OutputBuffer = workingBuffer;
_z.NextOut = 0;
_z.AvailableBytesOut = _workingBuffer.Length;
int rc = (_wantCompress)
? _z.Deflate(FlushType.Finish)
: _z.Inflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
{
string verb = (_wantCompress ? "de" : "in") + "flating";
if (_z.Message == null)
throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc));
else
throw new ZlibException(verb + ": " + _z.Message);
}
if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
{
_stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
}
done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;
// If GZIP and de-compress, we're done when 8 bytes remain.
if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress)
done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0);
}
while (!done);
Flush();
// workitem 7159
if (_flavor == ZlibStreamFlavor.GZIP)
{
if (_wantCompress)
{
// Emit the GZIP trailer: CRC32 and size mod 2^32
int c1 = crc.Crc32Result;
_stream.Write(BitConverter.GetBytes(c1), 0, 4);
int c2 = (Int32)(crc.TotalBytesRead & 0x00000000FFFFFFFF);
_stream.Write(BitConverter.GetBytes(c2), 0, 4);
}
else
{
throw new ZlibException("Writing with decompression is not supported.");
}
}
}
// workitem 7159
else if (_streamMode == StreamMode.Reader)
{
if (_flavor == ZlibStreamFlavor.GZIP)
{
if (!_wantCompress)
{
// workitem 8501: handle edge case (decompress empty stream)
if (_z.TotalBytesOut == 0L)
return;
// Read and potentially verify the GZIP trailer:
// CRC32 and size mod 2^32
byte[] trailer = new byte[8];
// workitems 8679 & 12554
if (_z.AvailableBytesIn < 8)
{
// Make sure we have read to the end of the stream
Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, _z.AvailableBytesIn);
int bytesNeeded = 8 - _z.AvailableBytesIn;
int bytesRead = _stream.Read(trailer,
_z.AvailableBytesIn,
bytesNeeded);
if (bytesNeeded != bytesRead)
{
throw new ZlibException(String.Format("Missing or incomplete GZIP trailer. Expected 8 bytes, got {0}.",
_z.AvailableBytesIn + bytesRead));
}
}
else
{
Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, trailer.Length);
}
Int32 crc32_expected = BitConverter.ToInt32(trailer, 0);
Int32 crc32_actual = crc.Crc32Result;
Int32 isize_expected = BitConverter.ToInt32(trailer, 4);
Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF);
if (crc32_actual != crc32_expected)
throw new ZlibException(String.Format("Bad CRC32 in GZIP trailer. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected));
if (isize_actual != isize_expected)
throw new ZlibException(String.Format("Bad size in GZIP trailer. (actual({0})!=expected({1}))", isize_actual, isize_expected));
}
else
{
throw new ZlibException("Reading with compression is not supported.");
}
}
}
}
private void end()
{
if (z == null)
return;
if (_wantCompress)
{
_z.EndDeflate();
}
else
{
_z.EndInflate();
}
_z = null;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!disposing)
{
return;
}
if (_stream == null) return;
try
{
finish();
}
finally
{
end();
if (!_leaveOpen) _stream.Dispose();
_stream = null;
}
}
public override void Flush()
{
_stream.Flush();
}
public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
//_outStream.Seek(offset, origin);
}
public override void SetLength(System.Int64 value)
{
_stream.SetLength(value);
}
#if NOT
public int Read()
{
if (Read(_buf1, 0, 1) == 0)
return 0;
// calculate CRC after reading
if (crc!=null)
crc.SlurpBlock(_buf1,0,1);
return (_buf1[0] & 0xFF);
}
#endif
private bool nomoreinput = false;
private string ReadZeroTerminatedString()
{
var list = new System.Collections.Generic.List<byte>();
bool done = false;
do
{
// workitem 7740
int n = _stream.Read(_buf1, 0, 1);
if (n != 1)
throw new ZlibException("Unexpected EOF reading GZIP header.");
else
{
if (_buf1[0] == 0)
done = true;
else
list.Add(_buf1[0]);
}
} while (!done);
byte[] a = list.ToArray();
return GZipStream.iso8859dash1.GetString(a, 0, a.Length);
}
private int _ReadAndValidateGzipHeader()
{
int totalBytesRead = 0;
// read the header on the first read
byte[] header = new byte[10];
int n = _stream.Read(header, 0, header.Length);
// workitem 8501: handle edge case (decompress empty stream)
if (n == 0)
return 0;
if (n != 10)
throw new ZlibException("Not a valid GZIP stream.");
if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8)
throw new ZlibException("Bad GZIP header.");
Int32 timet = BitConverter.ToInt32(header, 4);
_GzipMtime = GZipStream._unixEpoch.AddSeconds(timet);
totalBytesRead += n;
if ((header[3] & 0x04) == 0x04)
{
// read and discard extra field
n = _stream.Read(header, 0, 2); // 2-byte length field
totalBytesRead += n;
Int16 extraLength = (Int16)(header[0] + header[1] * 256);
byte[] extra = new byte[extraLength];
n = _stream.Read(extra, 0, extra.Length);
if (n != extraLength)
throw new ZlibException("Unexpected end-of-file reading GZIP header.");
totalBytesRead += n;
}
if ((header[3] & 0x08) == 0x08)
_GzipFileName = ReadZeroTerminatedString();
if ((header[3] & 0x10) == 0x010)
_GzipComment = ReadZeroTerminatedString();
if ((header[3] & 0x02) == 0x02)
Read(_buf1, 0, 1); // CRC16, ignore
return totalBytesRead;
}
public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
{
// According to MS documentation, any implementation of the IO.Stream.Read function must:
// (a) throw an exception if offset & count reference an invalid part of the buffer,
// or if count < 0, or if buffer is null
// (b) return 0 only upon EOF, or if count = 0
// (c) if not EOF, then return at least 1 byte, up to <count> bytes
if (_streamMode == StreamMode.Undefined)
{
if (!this._stream.CanRead) throw new ZlibException("The stream is not readable.");
// for the first read, set up some controls.
_streamMode = StreamMode.Reader;
// (The first reference to _z goes through the private accessor which
// may initialize it.)
z.AvailableBytesIn = 0;
if (_flavor == ZlibStreamFlavor.GZIP)
{
_gzipHeaderByteCount = _ReadAndValidateGzipHeader();
// workitem 8501: handle edge case (decompress empty stream)
if (_gzipHeaderByteCount == 0)
return 0;
}
}
if (_streamMode != StreamMode.Reader)
throw new ZlibException("Cannot Read after Writing.");
if (count == 0) return 0;
if (nomoreinput && _wantCompress) return 0; // workitem 8557
if (buffer == null) throw new ArgumentNullException("buffer");
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset");
if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count");
int rc = 0;
// set up the output of the deflate/inflate codec:
_z.OutputBuffer = buffer;
_z.NextOut = offset;
_z.AvailableBytesOut = count;
// This is necessary in case _workingBuffer has been resized. (new byte[])
// (The first reference to _workingBuffer goes through the private accessor which
// may initialize it.)
_z.InputBuffer = workingBuffer;
do
{
// need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any.
if ((_z.AvailableBytesIn == 0) && (!nomoreinput))
{
// No data available, so try to Read data from the captive stream.
_z.NextIn = 0;
_z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length);
if (_z.AvailableBytesIn == 0)
nomoreinput = true;
}
// we have data in InputBuffer; now compress or decompress as appropriate
rc = (_wantCompress)
? _z.Deflate(_flushMode)
: _z.Inflate(_flushMode);
if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR))
return 0;
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message));
if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count))
break; // nothing more to read
}
//while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK);
while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK);
// workitem 8557
// is there more room in output?
if (_z.AvailableBytesOut > 0)
{
if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0)
{
// deferred
}
// are we completely done reading?
if (nomoreinput)
{
// and in compression?
if (_wantCompress)
{
// no more input data available; therefore we flush to
// try to complete the read
rc = _z.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message));
}
}
}
rc = (count - _z.AvailableBytesOut);
// calculate CRC after reading
if (crc != null)
crc.SlurpBlock(buffer, offset, rc);
return rc;
}
public override System.Boolean CanRead
{
get { return this._stream.CanRead; }
}
public override System.Boolean CanSeek
{
get { return this._stream.CanSeek; }
}
public override System.Boolean CanWrite
{
get { return this._stream.CanWrite; }
}
public override System.Int64 Length
{
get { return _stream.Length; }
}
public override long Position
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
internal enum StreamMode
{
Writer,
Reader,
Undefined,
}
public static void CompressString(String s, Stream compressor)
{
byte[] uncompressed = System.Text.Encoding.UTF8.GetBytes(s);
using (compressor)
{
compressor.Write(uncompressed, 0, uncompressed.Length);
}
}
public static void CompressBuffer(byte[] b, Stream compressor)
{
// workitem 8460
using (compressor)
{
compressor.Write(b, 0, b.Length);
}
}
public static String UncompressString(byte[] compressed, Stream decompressor)
{
// workitem 8460
byte[] working = new byte[1024];
var encoding = System.Text.Encoding.UTF8;
using (var output = new MemoryStream())
{
using (decompressor)
{
int n;
while ((n = decompressor.Read(working, 0, working.Length)) != 0)
{
output.Write(working, 0, n);
}
}
// reset to allow read from start
output.Seek(0, SeekOrigin.Begin);
var sr = new StreamReader(output, encoding);
return sr.ReadToEnd();
}
}
public static byte[] UncompressBuffer(byte[] compressed, Stream decompressor)
{
// workitem 8460
byte[] working = new byte[1024];
using (var output = new MemoryStream())
{
using (decompressor)
{
int n;
while ((n = decompressor.Read(working, 0, working.Length)) != 0)
{
output.Write(working, 0, n);
}
}
return output.ToArray();
}
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace FickleFrostbite.FIT
{
/// <summary>
/// Implements the Goal profile message.
/// </summary>
public class GoalMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public GoalMesg() : base(Profile.mesgs[Profile.GoalIndex])
{
}
public GoalMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the MessageIndex field</summary>
/// <returns>Returns nullable ushort representing the MessageIndex field</returns>
public ushort? GetMessageIndex()
{
return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set MessageIndex field</summary>
/// <param name="messageIndex_">Nullable field value to be set</param>
public void SetMessageIndex(ushort? messageIndex_)
{
SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Sport field</summary>
/// <returns>Returns nullable Sport enum representing the Sport field</returns>
public Sport? GetSport()
{
object obj = GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
Sport? value = obj == null ? (Sport?)null : (Sport)obj;
return value;
}
/// <summary>
/// Set Sport field</summary>
/// <param name="sport_">Nullable field value to be set</param>
public void SetSport(Sport? sport_)
{
SetFieldValue(0, 0, sport_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SubSport field</summary>
/// <returns>Returns nullable SubSport enum representing the SubSport field</returns>
public SubSport? GetSubSport()
{
object obj = GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
SubSport? value = obj == null ? (SubSport?)null : (SubSport)obj;
return value;
}
/// <summary>
/// Set SubSport field</summary>
/// <param name="subSport_">Nullable field value to be set</param>
public void SetSubSport(SubSport? subSport_)
{
SetFieldValue(1, 0, subSport_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the StartDate field</summary>
/// <returns>Returns DateTime representing the StartDate field</returns>
public DateTime GetStartDate()
{
return TimestampToDateTime((uint?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set StartDate field</summary>
/// <param name="startDate_">Nullable field value to be set</param>
public void SetStartDate(DateTime startDate_)
{
SetFieldValue(2, 0, startDate_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the EndDate field</summary>
/// <returns>Returns DateTime representing the EndDate field</returns>
public DateTime GetEndDate()
{
return TimestampToDateTime((uint?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set EndDate field</summary>
/// <param name="endDate_">Nullable field value to be set</param>
public void SetEndDate(DateTime endDate_)
{
SetFieldValue(3, 0, endDate_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Type field</summary>
/// <returns>Returns nullable Goal enum representing the Type field</returns>
new public Goal? GetType()
{
object obj = GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
Goal? value = obj == null ? (Goal?)null : (Goal)obj;
return value;
}
/// <summary>
/// Set Type field</summary>
/// <param name="type_">Nullable field value to be set</param>
public void SetType(Goal? type_)
{
SetFieldValue(4, 0, type_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Value field</summary>
/// <returns>Returns nullable uint representing the Value field</returns>
public uint? GetValue()
{
return (uint?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Value field</summary>
/// <param name="value_">Nullable field value to be set</param>
public void SetValue(uint? value_)
{
SetFieldValue(5, 0, value_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Repeat field</summary>
/// <returns>Returns nullable Bool enum representing the Repeat field</returns>
public Bool? GetRepeat()
{
object obj = GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
Bool? value = obj == null ? (Bool?)null : (Bool)obj;
return value;
}
/// <summary>
/// Set Repeat field</summary>
/// <param name="repeat_">Nullable field value to be set</param>
public void SetRepeat(Bool? repeat_)
{
SetFieldValue(6, 0, repeat_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TargetValue field</summary>
/// <returns>Returns nullable uint representing the TargetValue field</returns>
public uint? GetTargetValue()
{
return (uint?)GetFieldValue(7, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TargetValue field</summary>
/// <param name="targetValue_">Nullable field value to be set</param>
public void SetTargetValue(uint? targetValue_)
{
SetFieldValue(7, 0, targetValue_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Recurrence field</summary>
/// <returns>Returns nullable GoalRecurrence enum representing the Recurrence field</returns>
public GoalRecurrence? GetRecurrence()
{
object obj = GetFieldValue(8, 0, Fit.SubfieldIndexMainField);
GoalRecurrence? value = obj == null ? (GoalRecurrence?)null : (GoalRecurrence)obj;
return value;
}
/// <summary>
/// Set Recurrence field</summary>
/// <param name="recurrence_">Nullable field value to be set</param>
public void SetRecurrence(GoalRecurrence? recurrence_)
{
SetFieldValue(8, 0, recurrence_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the RecurrenceValue field</summary>
/// <returns>Returns nullable ushort representing the RecurrenceValue field</returns>
public ushort? GetRecurrenceValue()
{
return (ushort?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set RecurrenceValue field</summary>
/// <param name="recurrenceValue_">Nullable field value to be set</param>
public void SetRecurrenceValue(ushort? recurrenceValue_)
{
SetFieldValue(9, 0, recurrenceValue_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Enabled field</summary>
/// <returns>Returns nullable Bool enum representing the Enabled field</returns>
public Bool? GetEnabled()
{
object obj = GetFieldValue(10, 0, Fit.SubfieldIndexMainField);
Bool? value = obj == null ? (Bool?)null : (Bool)obj;
return value;
}
/// <summary>
/// Set Enabled field</summary>
/// <param name="enabled_">Nullable field value to be set</param>
public void SetEnabled(Bool? enabled_)
{
SetFieldValue(10, 0, enabled_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
using System;
using System.Drawing;
using MonoMac.AppKit;
namespace GLFullScreen
{
public partial class MainWindowController : MonoMac.AppKit.NSWindowController
{
bool isInFullScreenMode;
// full-screen mode
NSWindow fullScreenWindow;
MyOpenGLView fullScreenView;
Scene scene;
bool isAnimating;
double renderTime;
// Call to load from the XIB/NIB file
public MainWindowController () : base("MainWindow")
{
}
public override void AwakeFromNib ()
{
// Allocate the scene object
scene = new Scene ();
// Assign the view's MainController to us
openGLView.MainController = this;
// reset the viewport and update OpenGL Context
openGLView.UpdateView ();
// Activate the display link now
openGLView.StartAnimation ();
isAnimating = true;
}
partial void goFullScreen (NSButton sender)
{
isInFullScreenMode = true;
// Pause the non-fullscreen view
openGLView.StopAnimation ();
RectangleF mainDisplayRect;
RectangleF viewRect;
// Create a screen-sized window on the display you want to take over
// Note, mainDisplayRect has a non-zero origin if the key window is on a secondary display
mainDisplayRect = NSScreen.MainScreen.Frame;
fullScreenWindow = new NSWindow (mainDisplayRect, NSWindowStyle.Borderless, NSBackingStore.Buffered, true);
// Set the window level to be above the menu bar
fullScreenWindow.Level = NSWindowLevel.MainMenu + 1;
// Perform any other window configuration you desire
fullScreenWindow.IsOpaque = true;
fullScreenWindow.HidesOnDeactivate = true;
// Create a view with a double-buffered OpenGL context and attach it to the window
// By specifying the non-fullscreen context as the shareContext, we automatically inherit the
// OpenGL objects (textures, etc) it has defined
viewRect = new RectangleF (0, 0, mainDisplayRect.Size.Width, mainDisplayRect.Size.Height);
fullScreenView = new MyOpenGLView (viewRect, openGLView.OpenGLContext);
fullScreenWindow.ContentView = fullScreenView;
// Show the window
fullScreenWindow.MakeKeyAndOrderFront (this);
// Set the scene with the full-screen viewport and viewing transformation
Scene.setViewportRect (viewRect);
// Assign the view's MainController to self
fullScreenView.MainController = this;
if (!isAnimating) {
// Mark the view as needing drawing to initalize its contents
fullScreenView.NeedsDisplay = true;
} else {
// Start playing the animation
fullScreenView.StartAnimation ();
}
}
public void goWindow ()
{
isInFullScreenMode = false;
// use OrderOut here instead of Close or nasty things will happen with Garbage Collection and a double free
fullScreenWindow.OrderOut (this);
fullScreenView.DeAllocate ();
fullScreenWindow.Dispose ();
fullScreenWindow = null;
// Switch to the non-fullscreen context
openGLView.OpenGLContext.MakeCurrentContext ();
if (!isAnimating) {
// Mark the view as needing drawing
// The animation has advanced while we were in full-screen mode, so its current contents are stale
openGLView.NeedsDisplay = true;
} else {
// continue playing the animation
openGLView.StartAnimation ();
}
}
public void startAnimation ()
{
if (isAnimating)
return;
if (!isInFullScreenMode)
openGLView.StartAnimation ();
else
fullScreenView.StartAnimation ();
isAnimating = true;
}
public void stopAnimation ()
{
if (!isAnimating)
return;
if (!isInFullScreenMode)
openGLView.StopAnimation ();
else
fullScreenView.StopAnimation ();
isAnimating = false;
}
public override void KeyDown (NSEvent theEvent)
{
var c = theEvent.CharactersIgnoringModifiers[0];
switch (c) {
// [Esc] exits full-screen mode
case (char)27:
if (isInFullScreenMode)
goWindow ();
break;
// [space] toggles rotation of the globe
case (char)32:
toggleAnimation ();
break;
case 'w':
case 'W':
Scene.toggleWireFrame ();
break;
default:
break;
}
}
public void toggleAnimation ()
{
if (isAnimating)
stopAnimation ();
else
startAnimation ();
}
public Scene Scene {
get { return scene; }
}
public double RenderTime {
get { return renderTime; }
set { renderTime = value; }
}
// Holding the mouse button and dragging the mouse changes the "roll" angle (y-axis) and the direction from which sunlight is coming (x-axis).
public override void MouseDown (NSEvent theEvent)
{
bool dragging = true;
PointF windowPoint;
PointF lastWindowPoint = theEvent.LocationInWindow;
float dx, dy;
bool wasAnimating = isAnimating;
if (wasAnimating)
stopAnimation ();
while (dragging) {
theEvent = openGLView.Window.NextEventMatchingMask (NSEventMask.LeftMouseUp | NSEventMask.LeftMouseDragged);
windowPoint = theEvent.LocationInWindow;
switch (theEvent.Type) {
case NSEventType.LeftMouseUp:
dragging = false;
break;
case NSEventType.LeftMouseDragged:
dx = windowPoint.X - lastWindowPoint.X;
dy = windowPoint.Y - lastWindowPoint.Y;
Scene.SunAngle = Scene.SunAngle - 1 * dx;
Scene.RollAngle = Scene.RollAngle - 0.5f * dy;
lastWindowPoint = windowPoint;
if (isInFullScreenMode) {
fullScreenView.Display ();
}
else {
openGLView.Display ();
}
break;
default:
break;
}
}
if (wasAnimating) {
startAnimation ();
RenderTime = DateTime.Now.TimeOfDay.TotalMilliseconds;
}
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocTypeEditDyna
// ObjectType: DocTypeEditDyna
// CSLAType: DynamicEditableRoot
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using DocStore.Business.Security;
using UsingLibrary;
namespace DocStore.Business
{
/// <summary>
/// Types of document (dynamic root object).<br/>
/// This is a generated <see cref="DocTypeEditDyna"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="DocTypeEditDynaColl"/> collection.
/// </remarks>
[Serializable]
public partial class DocTypeEditDyna : MyBusinessBase<DocTypeEditDyna>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="DocTypeID"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> DocTypeIDProperty = RegisterProperty<int>(p => p.DocTypeID, "Doc Type ID");
/// <summary>
/// Gets the Doc Type ID.
/// </summary>
/// <value>The Doc Type ID.</value>
public int DocTypeID
{
get { return GetProperty(DocTypeIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DocTypeName"/> property.
/// </summary>
public static readonly PropertyInfo<string> DocTypeNameProperty = RegisterProperty<string>(p => p.DocTypeName, "Doc Type Name");
/// <summary>
/// Gets or sets the Doc Type Name.
/// </summary>
/// <value>The Doc Type Name.</value>
public string DocTypeName
{
get { return GetProperty(DocTypeNameProperty); }
set { SetProperty(DocTypeNameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
/// <summary>
/// Date of creation
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CreateUserIDProperty = RegisterProperty<int>(p => p.CreateUserID, "Create User ID");
/// <summary>
/// ID of the creating user
/// </summary>
/// <value>The Create User ID.</value>
public int CreateUserID
{
get { return GetProperty(CreateUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Date of last change
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> ChangeUserIDProperty = RegisterProperty<int>(p => p.ChangeUserID, "Change User ID");
/// <summary>
/// ID of the last changing user
/// </summary>
/// <value>The Change User ID.</value>
public int ChangeUserID
{
get { return GetProperty(ChangeUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RowVersion"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version");
/// <summary>
/// Row version counter for concurrency control
/// </summary>
/// <value>The Row Version.</value>
public byte[] RowVersion
{
get { return GetProperty(RowVersionProperty); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="DocTypeEditDyna"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="DocTypeEditDyna"/> object.</returns>
internal static DocTypeEditDyna NewDocTypeEditDyna()
{
return DataPortal.Create<DocTypeEditDyna>();
}
/// <summary>
/// Factory method. Loads a <see cref="DocTypeEditDyna"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="DocTypeEditDyna"/> object.</returns>
internal static DocTypeEditDyna GetDocTypeEditDyna(SafeDataReader dr)
{
DocTypeEditDyna obj = new DocTypeEditDyna();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
/// <summary>
/// Factory method. Deletes a <see cref="DocTypeEditDyna"/> object, based on given parameters.
/// </summary>
/// <param name="docTypeID">The DocTypeID of the DocTypeEditDyna to delete.</param>
internal static void DeleteDocTypeEditDyna(int docTypeID)
{
DataPortal.Delete<DocTypeEditDyna>(docTypeID);
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="DocTypeEditDyna"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
internal static void NewDocTypeEditDyna(EventHandler<DataPortalResult<DocTypeEditDyna>> callback)
{
DataPortal.BeginCreate<DocTypeEditDyna>(callback);
}
/// <summary>
/// Factory method. Asynchronously deletes a <see cref="DocTypeEditDyna"/> object, based on given parameters.
/// </summary>
/// <param name="docTypeID">The DocTypeID of the DocTypeEditDyna to delete.</param>
/// <param name="callback">The completion callback method.</param>
internal static void DeleteDocTypeEditDyna(int docTypeID, EventHandler<DataPortalResult<DocTypeEditDyna>> callback)
{
DataPortal.BeginDelete<DocTypeEditDyna>(docTypeID, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocTypeEditDyna"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocTypeEditDyna()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="DocTypeEditDyna"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(DocTypeIDProperty, System.Threading.Interlocked.Decrement(ref _lastId));
LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
LoadProperty(CreateUserIDProperty, UserInformation.UserId);
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty));
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="DocTypeEditDyna"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(DocTypeIDProperty, dr.GetInt32("DocTypeID"));
LoadProperty(DocTypeNameProperty, dr.GetString("DocTypeName"));
LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true));
LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID"));
LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true));
LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID"));
LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]);
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="DocTypeEditDyna"/> object in the database.
/// </summary>
protected override void DataPortal_Insert()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("AddDocTypeEditDyna", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocTypeID", ReadProperty(DocTypeIDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@DocTypeName", ReadProperty(DocTypeNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(DocTypeIDProperty, (int) cmd.Parameters["@DocTypeID"].Value);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="DocTypeEditDyna"/> object.
/// </summary>
protected override void DataPortal_Update()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("UpdateDocTypeEditDyna", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocTypeID", ReadProperty(DocTypeIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@DocTypeName", ReadProperty(DocTypeNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
private void SimpleAuditTrail()
{
LoadProperty(ChangeDateProperty, DateTime.Now);
LoadProperty(ChangeUserIDProperty, UserInformation.UserId);
if (IsNew)
{
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty));
}
}
/// <summary>
/// Self deletes the <see cref="DocTypeEditDyna"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(DocTypeID);
}
/// <summary>
/// Deletes the <see cref="DocTypeEditDyna"/> object from database.
/// </summary>
/// <param name="docTypeID">The delete criteria.</param>
protected void DataPortal_Delete(int docTypeID)
{
// audit the object, just in case soft delete is used on this object
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("DeleteDocTypeEditDyna", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocTypeID", docTypeID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, docTypeID);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
ctx.Commit();
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace System.Management.Automation
{
/// <summary>
/// Represents a variable in the PowerShell language.
/// </summary>
public class PSVariable : IHasSessionStateEntryVisibility
{
#region Ctor
/// <summary>
/// Constructs a variable with the given name.
/// </summary>
///
/// <param name="name">
/// The name of the variable.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
public PSVariable(string name)
: this(name, null, ScopedItemOptions.None, (Collection<Attribute>)null)
{
}
/// <summary>
/// Constructs a variable with the given name, and value.
/// </summary>
///
/// <param name="name">
/// The name of the variable.
/// </param>
///
/// <param name="value">
/// The value of the variable.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
public PSVariable(string name, object value)
: this(name, value, ScopedItemOptions.None, (Collection<Attribute>)null)
{
}
/// <summary>
/// Constructs a variable with the given name, value, and options.
/// </summary>
///
/// <param name="name">
/// The name of the variable.
/// </param>
///
/// <param name="value">
/// The value of the variable.
/// </param>
///
/// <param name="options">
/// The constraints of the variable. Note, variables can only be made constant
/// in the constructor.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
public PSVariable(string name, object value, ScopedItemOptions options)
: this(name, value, options, (Collection<Attribute>)null)
{
}
/// <summary>
/// Constructs a variable with the given name, value, options, and description.
/// </summary>
///
/// <param name="name">
/// The name of the variable.
/// </param>
///
/// <param name="value">
/// The value of the variable.
/// </param>
///
/// <param name="options">
/// The constraints of the variable. Note, variables can only be made constant
/// in the constructor.
/// </param>
///
/// <param name="description">
/// The description for the variable.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
internal PSVariable(string name, object value, ScopedItemOptions options, string description)
: this(name, value, options, (Collection<Attribute>)null)
{
_description = description;
}
/// <summary>
/// Constructs a variable with the given name, value, options, and description.
/// </summary>
///
/// <param name="name">
/// The name of the variable.
/// </param>
///
/// <param name="value">
/// The value of the variable.
/// </param>
///
/// <param name="options">
/// The constraints of the variable. Note, variables can only be made constant
/// in the constructor.
/// </param>
///
/// <param name="attributes">
/// The attributes for the variable. ValidateArgumentsAttribute and derived types
/// will be used to validate a value before setting it.
/// </param>
///
/// <param name="description">
/// The description for the variable.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
internal PSVariable(
string name,
object value,
ScopedItemOptions options,
Collection<Attribute> attributes,
string description)
: this(name, value, options, attributes)
{
_description = description;
}
/// <summary>
/// Constructs a variable with the given name, value, options, and attributes
/// </summary>
///
/// <param name="name">
/// The name of the variable.
/// </param>
///
/// <param name="value">
/// The value of the variable.
/// </param>
///
/// <param name="options">
/// The constraints of the variable. Note, variables can only be made constant
/// in the constructor.
/// </param>
///
/// <param name="attributes">
/// The attributes for the variable. ValidateArgumentsAttribute and derived types
/// will be used to validate a value before setting it.
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
///
/// <exception cref="ValidationMetadataException">
/// If the validation metadata identified in <paramref name="attributes"/>
/// throws an exception.
/// </exception>
public PSVariable(
string name,
object value,
ScopedItemOptions options,
Collection<Attribute> attributes)
{
if (String.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentException("name");
}
Name = name;
_attributes = new PSVariableAttributeCollection(this);
// Note, it is OK to set the value before setting the attributes
// because each attribute will be validated as it is set.
SetValueRawImpl(value, true);
if (attributes != null)
{
foreach (Attribute attribute in attributes)
{
_attributes.Add(attribute);
}
}
// Set the options after setting the initial value.
_options = options;
if (IsAllScope)
{
Language.VariableAnalysis.NoteAllScopeVariable(name);
}
}
// Should be protected, but that makes it public which we don't want.
// The dummy parameter is to make the signature distinct from the public constructor taking a string.
// This constructor exists to avoid calling SetValueRaw, which when overridden, might not work because
// the derived class isn't fully constructed yet.
internal PSVariable(string name, bool dummy)
{
Name = name;
}
#endregion ctor
/// <summary>
/// Gets the name of the variable.
/// </summary>
public string Name { get; } = String.Empty;
/// <summary>
/// Gets or sets the description of the variable.
/// </summary>
public virtual string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
private string _description = String.Empty;
internal void DebuggerCheckVariableRead()
{
var context = SessionState != null
? SessionState.ExecutionContext
: LocalPipeline.GetExecutionContextFromTLS();
if (null != context && context._debuggingMode > 0)
{
context.Debugger.CheckVariableRead(Name);
}
}
internal void DebuggerCheckVariableWrite()
{
var context = SessionState != null
? SessionState.ExecutionContext
: LocalPipeline.GetExecutionContextFromTLS();
if (null != context && context._debuggingMode > 0)
{
context.Debugger.CheckVariableWrite(Name);
}
}
/// <summary>
/// Gets or sets the value of the variable
/// </summary>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the variable is read-only or constant upon call to set.
/// </exception>
///
/// <exception cref="ValidationMetadataException">
/// <paramref name="value"/> is not valid according to one or more
/// of the attributes of this shell variable.
/// </exception>
public virtual object Value
{
get
{
DebuggerCheckVariableRead();
return _value;
}
set
{
SetValue(value);
}
}
private object _value;
/// <summary>
/// If true, then this variable is visible outside the runspace.
/// </summary>
public SessionStateEntryVisibility Visibility { get; set; } = SessionStateEntryVisibility.Public;
/// <summary>
/// The module where this variable was defined.
/// </summary>
public PSModuleInfo Module { get; private set; }
internal void SetModule(PSModuleInfo module)
{
Module = module;
}
/// <summary>
/// The name of the module that defined this variable.
/// </summary>
public string ModuleName
{
get
{
if (Module != null)
return Module.Name;
return string.Empty;
}
}
/// <summary>
/// Gets or sets the scope options on the variable.
/// </summary>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// Upon set, if the variable is constant or if <paramref name="value"/>
/// contains the constant flag.
/// </exception>
public virtual ScopedItemOptions Options
{
get
{
return _options;
}
set
{
SetOptions(value, false);
}
}
internal void SetOptions(ScopedItemOptions newOptions, bool force)
{
// Check to see if the variable is constant or readonly, if so
// throw an exception because the options cannot be changed.
if (IsConstant || (!force && IsReadOnly))
{
SessionStateUnauthorizedAccessException e =
new SessionStateUnauthorizedAccessException(
Name,
SessionStateCategory.Variable,
"VariableNotWritable",
SessionStateStrings.VariableNotWritable);
throw e;
}
// Now check to see if the caller is trying to set
// the options to constant. This is only allowed at
// variable creation
if ((newOptions & ScopedItemOptions.Constant) != 0)
{
// user is trying to set the variable to constant after
// creating the variable. Do not allow this (as per spec).
SessionStateUnauthorizedAccessException e =
new SessionStateUnauthorizedAccessException(
Name,
SessionStateCategory.Variable,
"VariableCannotBeMadeConstant",
SessionStateStrings.VariableCannotBeMadeConstant);
throw e;
}
// Now check to see if the caller is trying to
// remove the AllScope option. This is not allowed
// at any time.
if (IsAllScope && ((newOptions & ScopedItemOptions.AllScope) == 0))
{
// user is trying to remove the AllScope option from the variable.
// Do not allow this (as per spec).
SessionStateUnauthorizedAccessException e =
new SessionStateUnauthorizedAccessException(
Name,
SessionStateCategory.Variable,
"VariableAllScopeOptionCannotBeRemoved",
SessionStateStrings.VariableAllScopeOptionCannotBeRemoved);
throw e;
}
_options = newOptions;
}
private ScopedItemOptions _options = ScopedItemOptions.None;
/// <summary>
/// Gets the collection that contains the attributes for the variable.
/// </summary>
///
/// <remarks>
/// To add or remove attributes, get the collection and then add or remove
/// attributes to that collection.
/// </remarks>
public Collection<Attribute> Attributes
{
get { return _attributes ?? (_attributes = new PSVariableAttributeCollection(this)); }
}
private PSVariableAttributeCollection _attributes;
/// <summary>
/// Checks if the given value meets the validation attribute constraints on the PSVariable.
/// </summary>
///
/// <param name="value">
/// value which needs to be checked
/// </param>
///
/// <remarks>
/// If <paramref name="value"/> is null or if no attributes are set, then
/// the value is deemed valid.
/// </remarks>
///
/// <exception cref="ValidationMetadataException">
/// If the validation metadata throws an exception.
/// </exception>
public virtual bool IsValidValue(object value)
{
return IsValidValue(_attributes, value);
}
internal static bool IsValidValue(IEnumerable<Attribute> attributes, object value)
{
if (attributes != null)
{
foreach (Attribute attribute in attributes)
{
if (!IsValidValue(value, attribute))
{
return false;
}
}
}
return true;
}
/// <summary>
/// Determines if the value is valid for the specified attribute
/// </summary>
///
/// <param name="value">
/// The variable value to validate.
/// </param>
///
/// <param name="attribute">
/// The attribute to use to validate that value.
/// </param>
///
/// <returns>
/// True if the value is valid with respect to the attribute, or false otherwise.
/// </returns>
internal static bool IsValidValue(object value, Attribute attribute)
{
bool result = true;
ValidateArgumentsAttribute validationAttribute = attribute as ValidateArgumentsAttribute;
if (validationAttribute != null)
{
try
{
// Get an EngineIntrinsics instance using the context of the thread.
ExecutionContext context = Runspaces.LocalPipeline.GetExecutionContextFromTLS();
EngineIntrinsics engine = null;
if (context != null)
{
engine = context.EngineIntrinsics;
}
validationAttribute.InternalValidate(value, engine);
}
catch (ValidationMetadataException)
{
result = false;
}
}
return result;
} // IsValidValue
/// <summary>
/// Runs all ArgumentTransformationAttributes that are specified in the Attributes
/// collection on the given value in the order that they are in the collection.
/// </summary>
///
/// <param name="attributes">
/// The attributes to use to transform the value.
/// </param>
/// <param name="value">
/// The value to be transformed.
/// </param>
///
/// <returns>
/// The transformed value.
/// </returns>
///
/// <exception cref="ArgumentTransformationMetadataException">
/// If the argument transformation fails.
/// </exception>
internal static object TransformValue(IEnumerable<Attribute> attributes, object value)
{
Diagnostics.Assert(attributes != null, "caller to verify attributes is not null");
object result = value;
// Get an EngineIntrinsics instance using the context of the thread.
ExecutionContext context = Runspaces.LocalPipeline.GetExecutionContextFromTLS();
EngineIntrinsics engine = null;
if (context != null)
{
engine = context.EngineIntrinsics;
}
foreach (Attribute attribute in attributes)
{
ArgumentTransformationAttribute transformationAttribute =
attribute as ArgumentTransformationAttribute;
if (transformationAttribute != null)
{
result = transformationAttribute.Transform(engine, result);
}
}
return result;
}
/// <summary>
/// Parameter binding does the checking and conversions as specified by the
/// attributes, so repeating that process is slow and wrong. This function
/// applies the attributes without repeating the checks.
/// </summary>
/// <param name="attributes">The list of attributes to add</param>
internal void AddParameterAttributesNoChecks(Collection<Attribute> attributes)
{
foreach (Attribute attribute in attributes)
{
_attributes.AddAttributeNoCheck(attribute);
}
}
#region internal members
/// <summary>
/// Returns true if the PSVariable is constant (only visible in the
/// current scope), false otherwise.
/// </summary>
///
internal bool IsConstant
{
get
{
return (_options & ScopedItemOptions.Constant) != 0;
}
} // IsConstant
/// <summary>
/// Returns true if the PSVariable is readonly (only visible in the
/// current scope), false otherwise.
/// </summary>
///
internal bool IsReadOnly
{
get
{
return (_options & ScopedItemOptions.ReadOnly) != 0;
}
} // IsReadOnly
/// <summary>
/// Returns true if the PSVariable is private (only visible in the
/// current scope), false otherwise.
/// </summary>
///
internal bool IsPrivate
{
get
{
return (_options & ScopedItemOptions.Private) != 0;
}
} // IsPrivate
/// <summary>
/// Returns true if the PSVariable is propagated to all scopes
/// when the scope is created.
/// </summary>
///
internal bool IsAllScope
{
get
{
return (_options & ScopedItemOptions.AllScope) != 0;
}
} // IsAllScope
/// <summary>
/// Indicates that the variable has been removed from session state
/// and should no longer be considered valid. This is necessary because
/// we surface variable references and can consequently not maintain
/// transparent integrity.
/// </summary>
internal bool WasRemoved
{
get
{
return _wasRemoved;
}
set
{
_wasRemoved = value;
// If set to true, clean up the variable...
if (value)
{
_options = ScopedItemOptions.None;
_value = null;
_wasRemoved = true;
_attributes = null;
}
}
}
private bool _wasRemoved;
internal SessionStateInternal SessionState { get; set; }
#endregion internal members
/// <summary>
/// Verifies the constraints and attributes before setting the value
/// </summary>
///
/// <param name="value">
/// The value to be set.
/// </param>
///
/// <exception cref="SessionStateUnauthorizedAccessException">
/// If the variable is read-only or constant.
/// </exception>
///
/// <exception cref="ValidationMetadataException">
/// If the validation metadata throws an exception or the value doesn't
/// pass the validation metadata.
/// </exception>
///
private void SetValue(object value)
{
// Check to see if the variable is writable
if ((_options & (ScopedItemOptions.ReadOnly | ScopedItemOptions.Constant)) != ScopedItemOptions.None)
{
SessionStateUnauthorizedAccessException e =
new SessionStateUnauthorizedAccessException(
Name,
SessionStateCategory.Variable,
"VariableNotWritable",
SessionStateStrings.VariableNotWritable);
throw e;
}
// Now perform all ArgumentTransformations that are needed
object transformedValue = value;
if (_attributes != null && _attributes.Count > 0)
{
transformedValue = TransformValue(_attributes, value);
// Next check to make sure the value is valid
if (!IsValidValue(transformedValue))
{
ValidationMetadataException e = new ValidationMetadataException(
"ValidateSetFailure",
null,
Metadata.InvalidValueFailure,
Name,
((transformedValue != null) ? transformedValue.ToString() : "$null"));
throw e;
}
}
if (transformedValue != null)
{
transformedValue = CopyMutableValues(transformedValue);
}
// Set the value before triggering any write breakpoints
_value = transformedValue;
DebuggerCheckVariableWrite();
}
private void SetValueRawImpl(object newValue, bool preserveValueTypeSemantics)
{
if (preserveValueTypeSemantics)
{
newValue = CopyMutableValues(newValue);
}
_value = newValue;
}
internal virtual void SetValueRaw(object newValue, bool preserveValueTypeSemantics)
{
SetValueRawImpl(newValue, preserveValueTypeSemantics);
}
private readonly CallSite<Func<CallSite, object, object>> _copyMutableValueSite =
CallSite<Func<CallSite, object, object>>.Create(PSVariableAssignmentBinder.Get());
internal object CopyMutableValues(object o)
{
// The variable assignment binder copies mutable values and returns other values as is.
return _copyMutableValueSite.Target.Invoke(_copyMutableValueSite, o);
}
internal void WrapValue()
{
if (!this.IsConstant)
{
if (_value != null)
{
_value = PSObject.AsPSObject(_value);
}
}
}
#if FALSE
// Replaced with a DLR based binder - but code is preserved in case that approach doesn't
// work well performance wise.
// See if it's a value type being assigned and
// make a copy if it is...
private static object PreserveValueType(object value)
{
if (value == null)
return null;
// Primitive types are immutable so just return them...
Type valueType = value.GetType();
if (valueType.IsPrimitive)
return value;
PSObject valueAsPSObject = value as PSObject;
if (valueAsPSObject != null)
{
object baseObject = valueAsPSObject.BaseObject;
if (baseObject != null)
{
valueType = baseObject.GetType();
if (valueType.IsValueType && !valueType.IsPrimitive)
{
return valueAsPSObject.Copy();
}
}
}
else if (valueType.IsValueType)
{
return PSObject.CopyValueType(value);
}
return value;
}
#endif
} // class PSVariable
internal class LocalVariable : PSVariable
{
private readonly MutableTuple _tuple;
private readonly int _tupleSlot;
public LocalVariable(string name, MutableTuple tuple, int tupleSlot)
: base(name, false)
{
_tuple = tuple;
_tupleSlot = tupleSlot;
}
public override ScopedItemOptions Options
{
get { return base.Options; }
set
{
// Throw, but only if someone is actually changing the options.
if (value != base.Options)
{
SessionStateUnauthorizedAccessException e =
new SessionStateUnauthorizedAccessException(
Name,
SessionStateCategory.Variable,
"VariableOptionsNotSettable",
SessionStateStrings.VariableOptionsNotSettable);
throw e;
}
}
}
public override object Value
{
get
{
DebuggerCheckVariableRead();
return _tuple.GetValue(_tupleSlot);
}
set
{
_tuple.SetValue(_tupleSlot, value);
DebuggerCheckVariableWrite();
}
}
internal override void SetValueRaw(object newValue, bool preserveValueTypeSemantics)
{
if (preserveValueTypeSemantics)
{
newValue = CopyMutableValues(newValue);
}
this.Value = newValue;
}
}
/// <summary>
/// This class is used for $null. It always returns null as a value and accepts
/// any value when it is set and throws it away.
/// </summary>
///
internal class NullVariable : PSVariable
{
/// <summary>
/// Constructor that calls the base class constructor with name "null" and
/// value null.
/// </summary>
///
internal NullVariable() : base(StringLiterals.Null, null, ScopedItemOptions.Constant | ScopedItemOptions.AllScope)
{
}
/// <summary>
/// Always returns null from get, and always accepts
/// but ignores the value on set.
/// </summary>
public override object Value
{
get
{
return null;
}
set
{
// All values are just ignored
}
}
/// <summary>
/// Gets the description for $null.
/// </summary>
public override string Description
{
get { return _description ?? (_description = SessionStateStrings.DollarNullDescription); }
set { /* Do nothing */ }
}
private string _description;
/// <summary>
/// Gets the scope options for $null which is always None.
/// </summary>
public override ScopedItemOptions Options
{
get { return ScopedItemOptions.None; }
set { /* Do nothing */ }
}
}
/// <summary>
/// The options that define some of the constraints for session state items like
/// variables, aliases, and functions.
/// </summary>
[Flags]
public enum ScopedItemOptions
{
/// <summary>
/// There are no constraints on the item.
/// </summary>
None = 0,
/// <summary>
/// The item is readonly. It can be removed but cannot be changed.
/// </summary>
ReadOnly = 0x1,
/// <summary>
/// The item cannot be removed or changed.
/// This flag can only be set a variable creation.
/// </summary>
Constant = 0x2,
/// <summary>
/// The item is private to the scope it was created in and
/// cannot be seen from child scopes.
/// </summary>
Private = 0x4,
/// <summary>
/// The item is propagated to each new child scope created.
/// </summary>
AllScope = 0x8,
/// <summary>
/// The option is not specified by the user
/// </summary>
Unspecified = 0x10
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
public class OfflineMessageModule : IRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool enabled = true;
private List<Scene> m_SceneList = new List<Scene>();
private string m_RestURL = String.Empty;
private bool m_ForwardOfflineGroupMessages = true;
public void Initialise(Scene scene, IConfigSource config)
{
if (!enabled)
return;
IConfig cnf = config.Configs["Messaging"];
if (cnf == null)
{
enabled = false;
return;
}
if (cnf != null && cnf.GetString(
"OfflineMessageModule", "None") !=
"OfflineMessageModule")
{
enabled = false;
return;
}
if (cnf != null)
m_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", m_ForwardOfflineGroupMessages);
lock (m_SceneList)
{
if (m_SceneList.Count == 0)
{
m_RestURL = cnf.GetString("OfflineMessageURL", "");
if (m_RestURL == "")
{
m_log.Error("[OFFLINE MESSAGING] Module was enabled, but no URL is given, disabling");
enabled = false;
return;
}
}
if (!m_SceneList.Contains(scene))
m_SceneList.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
}
}
public void PostInitialise()
{
if (!enabled)
return;
if (m_SceneList.Count == 0)
return;
IMessageTransferModule trans = m_SceneList[0].RequestModuleInterface<IMessageTransferModule>();
if (trans == null)
{
enabled = false;
lock (m_SceneList)
{
foreach (Scene s in m_SceneList)
s.EventManager.OnNewClient -= OnNewClient;
m_SceneList.Clear();
}
m_log.Error("[OFFLINE MESSAGING] No message transfer module is enabled. Diabling offline messages");
return;
}
trans.OnUndeliveredMessage += UndeliveredMessage;
m_log.Debug("[OFFLINE MESSAGING] Offline messages enabled");
}
public string Name
{
get { return "OfflineMessageModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
public void Close()
{
}
private Scene FindScene(UUID agentID)
{
foreach (Scene s in m_SceneList)
{
ScenePresence presence = s.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return s;
}
return null;
}
private IClientAPI FindClient(UUID agentID)
{
foreach (Scene s in m_SceneList)
{
ScenePresence presence = s.GetScenePresence(agentID);
if (presence != null && !presence.IsChildAgent)
return presence.ControllingClient;
}
return null;
}
private void OnNewClient(IClientAPI client)
{
client.OnRetrieveInstantMessages += RetrieveInstantMessages;
}
private void RetrieveInstantMessages(IClientAPI client)
{
if (m_RestURL != "")
{
m_log.DebugFormat("[OFFLINE MESSAGING] Retrieving stored messages for {0}", client.AgentId);
List<GridInstantMessage> msglist = SynchronousRestObjectPoster.BeginPostObject<UUID, List<GridInstantMessage>>(
"POST", m_RestURL + "/RetrieveMessages/", client.AgentId);
foreach (GridInstantMessage im in msglist)
{
// client.SendInstantMessage(im);
// Send through scene event manager so all modules get a chance
// to look at this message before it gets delivered.
//
// Needed for proper state management for stored group
// invitations
//
Scene s = FindScene(client.AgentId);
if (s != null)
s.EventManager.TriggerIncomingInstantMessage(im);
}
}
}
private void UndeliveredMessage(GridInstantMessage im)
{
if ((im.offline != 0)
&& (!im.fromGroup || (im.fromGroup && m_ForwardOfflineGroupMessages)))
{
bool success = SynchronousRestObjectPoster.BeginPostObject<GridInstantMessage, bool>(
"POST", m_RestURL+"/SaveMessage/", im);
if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
{
IClientAPI client = FindClient(new UUID(im.fromAgentID));
if (client == null)
return;
client.SendInstantMessage(new GridInstantMessage(
null, new UUID(im.toAgentID),
"System", new UUID(im.fromAgentID),
(byte)InstantMessageDialog.MessageFromAgent,
"User is not logged in. "+
(success ? "Message saved." : "Message not saved"),
false, new Vector3()));
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NetworkInterfacesOperations operations.
/// </summary>
public partial interface INetworkInterfacesOperations
{
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> GetWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveRouteListResult>> GetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> ListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about all network interfaces in a virtual machine
/// in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetVMNetworkInterfacesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetNetworkInterfacesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the specified network interface in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> GetVirtualMachineScaleSetNetworkInterfaceWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveRouteListResult>> BeginGetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> BeginListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about all network interfaces in a virtual machine
/// in a virtual machine scale set.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetVMNetworkInterfacesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a virtual machine scale set.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetNetworkInterfacesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using UnityEngine;
using InMobiAds;
using InMobiAds.Api;
// Example script showing how to invoke the InMobi Ads Unity plugin.
public class InMobiAdsDemoScript : MonoBehaviour
{
private BannerAd bannerAd;
private InterstitialAd interstitialAd;
private RewardedVideoAd rewardedVideoAd;
private float deltaTime = 0.0f;
public void Start ()
{
}
public void Update ()
{
// Calculate simple moving average for time to render screen. 0.1 factor used as smoothing
// value.
this.deltaTime += (Time.deltaTime - this.deltaTime) * 0.1f;
}
public void OnGUI ()
{
GUIStyle style = new GUIStyle ();
Rect rect = new Rect (0, 0, Screen.width, Screen.height);
style.alignment = TextAnchor.LowerRight;
style.fontSize = (int)(Screen.height * 0.06);
style.normal.textColor = new Color (0.0f, 0.0f, 0.5f, 1.0f);
float fps = 1.0f / this.deltaTime;
string text = string.Format ("{0:0.} fps", fps);
GUI.Label (rect, text, style);
// Puts some basic buttons onto the screen.
GUI.skin.button.fontSize = (int)(0.035f * Screen.width);
float buttonWidth = 0.35f * Screen.width;
float buttonHeight = 0.15f * Screen.height;
float columnOnePosition = 0.1f * Screen.width;
float columnTwoPosition = 0.55f * Screen.width;
Rect initializeInMobiAds = new Rect (
columnOnePosition,
0.05f * Screen.height,
buttonWidth,
buttonHeight);
if (GUI.Button (initializeInMobiAds, "Init InMobi SDK")) {
this.initializeInMobiAds ();
}
Rect requestBannerRect = new Rect (
columnOnePosition,
0.225f * Screen.height,
buttonWidth,
buttonHeight);
if (GUI.Button (requestBannerRect, "Request\nBanner")) {
this.RequestBanner ();
}
Rect destroyBannerRect = new Rect (
columnTwoPosition,
0.225f * Screen.height,
buttonWidth,
buttonHeight);
if (GUI.Button (destroyBannerRect, "Destroy\nBanner")) {
this.bannerAd.DestroyAd ();
}
Rect requestInterstitialRect = new Rect (
columnOnePosition,
0.4f * Screen.height,
buttonWidth,
buttonHeight);
if (GUI.Button (requestInterstitialRect, "Request\nInterstitial")) {
this.RequestInterstitial ();
}
Rect showInterstitialRect = new Rect (
columnOnePosition,
0.575f * Screen.height,
buttonWidth,
buttonHeight);
if (GUI.Button (showInterstitialRect, "Show\nInterstitial")) {
this.ShowInterstitial ();
}
Rect requestRewardedRect = new Rect (
columnTwoPosition,
0.4f * Screen.height,
buttonWidth,
buttonHeight);
if (GUI.Button (requestRewardedRect, "Request\nRewarded Video")) {
this.RequestRewardBasedVideo ();
}
Rect showRewardedRect = new Rect (
columnTwoPosition,
0.575f * Screen.height,
buttonWidth,
buttonHeight);
if (GUI.Button (showRewardedRect, "Show\nRewarded Video")) {
this.ShowRewardBasedVideo ();
}
}
private void initializeInMobiAds ()
{
InMobiPlugin inmobiPlugin = new InMobiPlugin ("4028cb8b2c3a0b45012c406824e800ba");
inmobiPlugin.SetLogLevel ("Debug");
inmobiPlugin.SetAge (23);
}
private void RequestBanner ()
{
// These ad units are configured to always serve test ads.
#if UNITY_ANDROID
string placementId = "1467162141987";
#elif UNITY_IPHONE
string placementId = "1464947431995";
#endif
// Create a 320x50 banner at the top of the screen.
this.bannerAd = new BannerAd (placementId, 320, 50, (int)InMobiAdPosition.TopCenter);
// Register for ad events.
this.bannerAd.OnAdLoadSucceeded += this.HandleOnAdLoadSucceeded;
this.bannerAd.OnAdLoadFailed += this.HandleAdLoadFailed;
this.bannerAd.OnAdDisplayed += this.HandleAdDisplayed;
this.bannerAd.OnAdDismissed += this.HandleAdDismissed;
this.bannerAd.OnAdInteraction += this.HandleAdInteraction;
this.bannerAd.OnUserLeftApplication += this.HandleUserLeftApplication;
// Load a banner ad.
this.bannerAd.LoadAd ();
}
private void RequestInterstitial ()
{
// These ad units are configured to always serve test ads.
#if UNITY_ANDROID
string placementId = "1469137441636";
#elif UNITY_IPHONE
string placementId = "1467548435003";
#endif
// Create an interstitial.
this.interstitialAd = new InterstitialAd (placementId);
// Register for ad events.
this.interstitialAd.OnAdLoadSucceeded += this.HandleOnAdLoadSucceeded;
this.interstitialAd.OnAdLoadFailed += this.HandleAdLoadFailed;
this.interstitialAd.OnAdDisplayed += this.HandleAdDisplayed;
this.interstitialAd.OnAdDismissed += this.HandleAdDismissed;
this.interstitialAd.OnAdInteraction += this.HandleAdInteraction;
this.interstitialAd.OnUserLeftApplication += this.HandleUserLeftApplication;
this.interstitialAd.OnAdReceived += this.HandleAdReceived;
this.interstitialAd.OnAdDisplayFailed += this.HandleAdDisplayFailed;
this.interstitialAd.OnAdWillDisplay += this.HandleAdWillDisplay;
// Load an interstitial ad.
this.interstitialAd.LoadAd ();
}
private void RequestRewardBasedVideo ()
{
#if UNITY_ANDROID
string placementId = "1465237901291";
#elif UNITY_IPHONE
string placementId = "1465883204802";
#endif
this.rewardedVideoAd = new RewardedVideoAd (placementId);
// Register for ad events.
this.rewardedVideoAd.OnAdLoadSucceeded += this.HandleOnAdLoadSucceeded;
this.rewardedVideoAd.OnAdLoadFailed += this.HandleAdLoadFailed;
this.rewardedVideoAd.OnAdDisplayed += this.HandleAdDisplayed;
this.rewardedVideoAd.OnAdDismissed += this.HandleAdDismissed;
this.rewardedVideoAd.OnAdInteraction += this.HandleAdInteraction;
this.rewardedVideoAd.OnUserLeftApplication += this.HandleUserLeftApplication;
this.rewardedVideoAd.OnAdReceived += this.HandleAdReceived;
this.rewardedVideoAd.OnAdDisplayFailed += this.HandleAdDisplayFailed;
this.rewardedVideoAd.OnAdWillDisplay += this.HandleAdWillDisplay;
this.rewardedVideoAd.OnAdRewardActionCompleted += this.HandleRewardActionCompleted;
this.rewardedVideoAd.LoadAd ();
}
private void ShowInterstitial ()
{
if (this.interstitialAd.isReady ()) {
this.interstitialAd.Show ();
} else {
MonoBehaviour.print ("Interstitial is not ready yet");
}
}
private void ShowRewardBasedVideo ()
{
if (this.rewardedVideoAd.isReady ()) {
this.rewardedVideoAd.Show ();
} else {
MonoBehaviour.print ("Rewarded video ad is not ready yet");
}
}
#region callback handlers
public void HandleOnAdLoadSucceeded (object sender, EventArgs args)
{
MonoBehaviour.print ("HandleOnAdLoadSucceded event received");
}
public void HandleAdLoadFailed (object sender, AdLoadFailedEventArgs args)
{
MonoBehaviour.print ("HandleAdLoadFailed event received with message: " + args.Error);
}
public void HandleAdDisplayed (object sender, EventArgs args)
{
MonoBehaviour.print ("HandleAdDisplayed event received");
}
public void HandleAdDismissed (object sender, EventArgs args)
{
MonoBehaviour.print ("HandleAdDismissed event received");
}
public void HandleAdInteraction (object sender, AdInteractionEventArgs args)
{
MonoBehaviour.print ("HandleAdDismissed event received " + args.Message);
}
public void HandleUserLeftApplication (object sender, EventArgs args)
{
MonoBehaviour.print ("HandleUserLeftApplication event received");
}
#endregion
#region Interstitial specific callback handlers
public void HandleAdReceived (object sender, EventArgs args)
{
MonoBehaviour.print ("HandleAdReceived event received");
}
public void HandleAdWillDisplay (object sender, EventArgs args)
{
MonoBehaviour.print (
"HandleAdWillDisplay event received with message: ");
}
public void HandleAdDisplayFailed (object sender, EventArgs args)
{
MonoBehaviour.print ("HandleAdDisplayFailed event received");
}
#endregion
#region RewardBasedVideo callback handlers
public void HandleRewardActionCompleted (object sender, AdRewardActionCompletedEventArgs args)
{
MonoBehaviour.print (
"HandleRewardActionCompleted event received for " + args.Rewards);
}
#endregion
}
| |
namespace Epi.Windows.Enter.Dialogs
{
/// <summary>
/// Auto Search
/// </summary>
partial class AutoSearchResults
{
/// <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);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
private void DELETE_ME_PLEASE_Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AutoSearchResults));
this.dataGrid1 = new System.Windows.Forms.DataGridView();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.lblRecordsReturned = new System.Windows.Forms.Label();
this.lblOKInstructions = new System.Windows.Forms.Label();
this.lblCancelInstructions = new System.Windows.Forms.Label();
this.lblContinueNewMessage = new System.Windows.Forms.Label();
this.lblContinueNew2 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
this.baseImageList.Images.SetKeyName(76, "");
this.baseImageList.Images.SetKeyName(77, "");
this.baseImageList.Images.SetKeyName(78, "");
this.baseImageList.Images.SetKeyName(79, "");
//
// dataGrid1
//
resources.ApplyResources(this.dataGrid1, "dataGrid1");
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.ReadOnly = true;
this.dataGrid1.DoubleClick += new System.EventHandler(this.dataGrid1_DoubleClick);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// lblRecordsReturned
//
resources.ApplyResources(this.lblRecordsReturned, "lblRecordsReturned");
this.lblRecordsReturned.Name = "lblRecordsReturned";
//
// lblOKInstructions
//
resources.ApplyResources(this.lblOKInstructions, "lblOKInstructions");
this.lblOKInstructions.Name = "lblOKInstructions";
//
// lblCancelInstructions
//
resources.ApplyResources(this.lblCancelInstructions, "lblCancelInstructions");
this.lblCancelInstructions.Name = "lblCancelInstructions";
//
// lblContinueNewMessage
//
resources.ApplyResources(this.lblContinueNewMessage, "lblContinueNewMessage");
this.lblContinueNewMessage.Name = "lblContinueNewMessage";
//
// lblContinueNew2
//
resources.ApplyResources(this.lblContinueNew2, "lblContinueNew2");
this.lblContinueNew2.Name = "lblContinueNew2";
//
// AutoSearchResults
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.lblContinueNew2);
this.Controls.Add(this.lblContinueNewMessage);
this.Controls.Add(this.lblCancelInstructions);
this.Controls.Add(this.lblOKInstructions);
this.Controls.Add(this.lblRecordsReturned);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.dataGrid1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AutoSearchResults";
this.ShowInTaskbar = false;
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView dataGrid1;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Label lblRecordsReturned;
private System.Windows.Forms.Label lblOKInstructions;
private System.Windows.Forms.Label lblCancelInstructions;
private System.Windows.Forms.Label lblContinueNewMessage;
private System.Windows.Forms.Label lblContinueNew2;
}
}
| |
// 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.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using EnvDTE;
using Microsoft.CodeAnalysis.Diagnostics.Log;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Text.Differencing;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PreviewPane
{
internal partial class PreviewPane : UserControl, IDisposable
{
private const double DefaultWidth = 400;
private static readonly string s_dummyThreeLineTitle = "A" + Environment.NewLine + "A" + Environment.NewLine + "A";
private static readonly Size s_infiniteSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
private readonly string _id;
private readonly bool _logIdVerbatimInTelemetry;
private readonly DTE _dte;
private bool _isExpanded;
private double _heightForThreeLineTitle;
private IWpfDifferenceViewer _previewDiffViewer;
public PreviewPane(
Image severityIcon,
string id,
string title,
string description,
Uri helpLink,
string helpLinkToolTipText,
IReadOnlyList<object> previewContent,
bool logIdVerbatimInTelemetry,
DTE dte,
Guid optionPageGuid = default(Guid))
{
InitializeComponent();
_id = id;
_logIdVerbatimInTelemetry = logIdVerbatimInTelemetry;
_dte = dte;
// Initialize header portion.
if ((severityIcon != null) && !string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(title))
{
HeaderStackPanel.Visibility = Visibility.Visible;
SeverityIconBorder.Child = severityIcon;
// Set the initial title text to three lines worth so that we can measure the pixel height
// that WPF requires to render three lines of text under the current font and DPI settings.
TitleRun.Text = s_dummyThreeLineTitle;
TitleTextBlock.Measure(availableSize: s_infiniteSize);
_heightForThreeLineTitle = TitleTextBlock.DesiredSize.Height;
// Now set the actual title text.
TitleRun.Text = title;
InitializeHyperlinks(helpLink, helpLinkToolTipText);
if (!string.IsNullOrWhiteSpace(description))
{
DescriptionParagraph.Inlines.Add(description);
}
}
_optionPageGuid = optionPageGuid;
if (optionPageGuid == default(Guid))
{
OptionsButton.Visibility = Visibility.Collapsed;
}
// Initialize preview (i.e. diff view) portion.
InitializePreviewElement(previewContent);
}
private void InitializePreviewElement(IReadOnlyList<object> previewItems)
{
var previewElement = CreatePreviewElement(previewItems);
if (previewElement != null)
{
HeaderSeparator.Visibility = Visibility.Visible;
PreviewDockPanel.Visibility = Visibility.Visible;
PreviewScrollViewer.Content = previewElement;
previewElement.VerticalAlignment = VerticalAlignment.Top;
previewElement.HorizontalAlignment = HorizontalAlignment.Left;
}
// 1. Width of the header section should not exceed the width of the preview content.
// In other words, the text we put in the header at the top of the preview pane
// should not cause the preview pane itself to grow wider than the width required to
// display the preview content at the bottom of the pane.
// 2. Adjust the height of the header section so that it displays only three lines worth
// by default.
AdjustWidthAndHeight(previewElement);
}
private FrameworkElement CreatePreviewElement(IReadOnlyList<object> previewItems)
{
if (previewItems == null || previewItems.Count == 0)
{
return null;
}
const int MaxItems = 3;
if (previewItems.Count > MaxItems)
{
previewItems = previewItems.Take(MaxItems).Concat("...").ToList();
}
var grid = new Grid();
for (var i = 0; i < previewItems.Count; i++)
{
var previewItem = previewItems[i];
FrameworkElement previewElement = null;
if (previewItem is IWpfDifferenceViewer)
{
_previewDiffViewer = (IWpfDifferenceViewer)previewItem;
previewElement = _previewDiffViewer.VisualElement;
PreviewDockPanel.Background = _previewDiffViewer.InlineView.Background;
}
else if (previewItem is string)
{
previewElement = GetPreviewForString((string)previewItem);
}
else if (previewItem is FrameworkElement)
{
previewElement = (FrameworkElement)previewItem;
}
var rowDefinition = i == 0 ? new RowDefinition() : new RowDefinition() { Height = GridLength.Auto };
grid.RowDefinitions.Add(rowDefinition);
Grid.SetRow(previewElement, grid.RowDefinitions.IndexOf(rowDefinition));
grid.Children.Add(previewElement);
if (i == 0)
{
grid.Width = previewElement.Width;
}
}
var preview = grid.Children.Count == 0 ? (FrameworkElement)grid.Children[0] : grid;
return preview;
}
private void InitializeHyperlinks(Uri helpLink, string helpLinkToolTipText)
{
IdHyperlink.SetVSHyperLinkStyle();
LearnMoreHyperlink.SetVSHyperLinkStyle();
IdHyperlink.Inlines.Add(_id);
IdHyperlink.NavigateUri = helpLink;
IdHyperlink.IsEnabled = true;
IdHyperlink.ToolTip = helpLinkToolTipText;
LearnMoreHyperlink.Inlines.Add(string.Format(ServicesVSResources.LearnMoreLinkText, _id));
LearnMoreHyperlink.NavigateUri = helpLink;
LearnMoreHyperlink.ToolTip = helpLinkToolTipText;
}
private static FrameworkElement GetPreviewForString(string previewContent)
{
return new TextBlock()
{
Margin = new Thickness(5),
VerticalAlignment = VerticalAlignment.Center,
Text = previewContent,
TextWrapping = TextWrapping.Wrap,
};
}
// This method adjusts the width of the header section to match that of the preview content
// thereby ensuring that the preview pane itself is never wider than the preview content.
// This method also adjusts the height of the header section so that it displays only three lines
// worth by default.
private void AdjustWidthAndHeight(FrameworkElement previewElement)
{
var headerStackPanelWidth = double.PositiveInfinity;
var titleTextBlockHeight = double.PositiveInfinity;
if (previewElement == null)
{
HeaderStackPanel.Measure(availableSize: s_infiniteSize);
headerStackPanelWidth = HeaderStackPanel.DesiredSize.Width;
TitleTextBlock.Measure(availableSize: s_infiniteSize);
titleTextBlockHeight = TitleTextBlock.DesiredSize.Height;
}
else
{
PreviewDockPanel.Measure(availableSize: new Size(
double.IsNaN(previewElement.Width) ? DefaultWidth : previewElement.Width,
double.PositiveInfinity));
headerStackPanelWidth = PreviewDockPanel.DesiredSize.Width;
if (IsNormal(headerStackPanelWidth))
{
TitleTextBlock.Measure(availableSize: new Size(headerStackPanelWidth, double.PositiveInfinity));
titleTextBlockHeight = TitleTextBlock.DesiredSize.Height;
}
}
if (IsNormal(headerStackPanelWidth))
{
HeaderStackPanel.Width = headerStackPanelWidth;
}
// If the pixel height required to render the complete title in the
// TextBlock is larger than that required to render three lines worth,
// then trim the contents of the TextBlock with an ellipsis at the end and
// display the expander button that will allow users to view the full text.
if (HasDescription || (IsNormal(titleTextBlockHeight) && (titleTextBlockHeight > _heightForThreeLineTitle)))
{
TitleTextBlock.MaxHeight = _heightForThreeLineTitle;
TitleTextBlock.TextTrimming = TextTrimming.CharacterEllipsis;
ExpanderToggleButton.Visibility = Visibility.Visible;
if (_isExpanded)
{
ExpanderToggleButton.IsChecked = true;
}
}
}
private static bool IsNormal(double size)
{
return size > 0 && !double.IsNaN(size) && !double.IsInfinity(size);
}
private bool HasDescription
{
get
{
return DescriptionParagraph.Inlines.Count > 0;
}
}
#region IDisposable Implementation
private bool _disposedValue = false;
private readonly Guid _optionPageGuid;
// VS editor will call Dispose at which point we should Close() the embedded IWpfDifferenceViewer.
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing && (_previewDiffViewer != null) && !_previewDiffViewer.IsClosed)
{
_previewDiffViewer.Close();
}
}
_disposedValue = true;
}
void IDisposable.Dispose()
{
Dispose(true);
}
#endregion
private void LearnMoreHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
if (e.Uri == null)
{
return;
}
BrowserHelper.StartBrowser(e.Uri);
e.Handled = true;
var hyperlink = sender as Hyperlink;
if (hyperlink == null)
{
return;
}
DiagnosticLogger.LogHyperlink(hyperlink.Name ?? "Preview", _id, HasDescription, _logIdVerbatimInTelemetry, e.Uri.AbsoluteUri);
}
private void ExpanderToggleButton_CheckedChanged(object sender, RoutedEventArgs e)
{
if (ExpanderToggleButton.IsChecked ?? false)
{
TitleTextBlock.MaxHeight = double.PositiveInfinity;
TitleTextBlock.TextTrimming = TextTrimming.None;
if (HasDescription)
{
DescriptionDockPanel.Visibility = Visibility.Visible;
if (LearnMoreHyperlink.NavigateUri != null)
{
LearnMoreTextBlock.Visibility = Visibility.Visible;
LearnMoreHyperlink.IsEnabled = true;
}
}
_isExpanded = true;
}
else
{
TitleTextBlock.MaxHeight = _heightForThreeLineTitle;
TitleTextBlock.TextTrimming = TextTrimming.CharacterEllipsis;
DescriptionDockPanel.Visibility = Visibility.Collapsed;
_isExpanded = false;
}
}
private void OptionsButton_Click(object sender, RoutedEventArgs e)
{
if (_optionPageGuid != default(Guid))
{
_dte.ExecuteCommand("Tools.Options", _optionPageGuid.ToString());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public abstract class Accept<T> : SocketTestHelperBase<T> where T : SocketHelperBase, new()
{
public Accept(ITestOutputHelper output) : base(output) { }
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public async Task Accept_Success(IPAddress listenAt)
{
using (Socket listen = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
int port = listen.BindToAnonymousPort(listenAt);
listen.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listen);
Assert.False(acceptTask.IsCompleted);
using (Socket client = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
await ConnectAsync(client, new IPEndPoint(listenAt, port));
Socket accept = await acceptTask;
Assert.NotNull(accept);
Assert.True(accept.Connected);
Assert.Equal(client.LocalEndPoint, accept.RemoteEndPoint);
Assert.Equal(accept.LocalEndPoint, client.RemoteEndPoint);
}
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(2)]
[InlineData(5)]
public async Task Accept_ConcurrentAcceptsBeforeConnects_Success(int numberAccepts)
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Listen(listener, numberAccepts);
var clients = new Socket[numberAccepts];
var servers = new Task<Socket>[numberAccepts];
try
{
for (int i = 0; i < numberAccepts; i++)
{
clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
servers[i] = AcceptAsync(listener);
}
foreach (Socket client in clients)
{
await ConnectAsync(client, listener.LocalEndPoint);
}
await Task.WhenAll(servers);
Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status));
Assert.All(servers, s => Assert.NotNull(s.Result));
Assert.All(servers, s => Assert.True(s.Result.Connected));
}
finally
{
foreach (Socket client in clients)
{
client?.Dispose();
}
foreach (Task<Socket> server in servers)
{
if (server?.Status == TaskStatus.RanToCompletion)
{
server.Result.Dispose();
}
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(2)]
[InlineData(5)]
public async Task Accept_ConcurrentAcceptsAfterConnects_Success(int numberAccepts)
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Listen(listener, numberAccepts);
var clients = new Socket[numberAccepts];
var clientConnects = new Task[numberAccepts];
var servers = new Task<Socket>[numberAccepts];
try
{
for (int i = 0; i < numberAccepts; i++)
{
clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientConnects[i] = ConnectAsync(clients[i], listener.LocalEndPoint);
}
for (int i = 0; i < numberAccepts; i++)
{
servers[i] = AcceptAsync(listener);
}
await Task.WhenAll(clientConnects);
Assert.All(clientConnects, c => Assert.Equal(TaskStatus.RanToCompletion, c.Status));
await Task.WhenAll(servers);
Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status));
Assert.All(servers, s => Assert.NotNull(s.Result));
Assert.All(servers, s => Assert.True(s.Result.Connected));
}
finally
{
foreach (Socket client in clients)
{
client?.Dispose();
}
foreach (Task<Socket> server in servers)
{
if (server?.Status == TaskStatus.RanToCompletion)
{
server.Result.Dispose();
}
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
public async Task Accept_WithTargetSocket_Success()
{
if (!SupportsAcceptIntoExistingSocket)
return;
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listener.BindToAnonymousPort(IPAddress.Loopback);
listener.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listener, server);
client.Connect(IPAddress.Loopback, port);
Socket accepted = await acceptTask;
Assert.Same(server, accepted);
Assert.True(accepted.Connected);
}
}
[ActiveIssue(22808, TargetFrameworkMonikers.NetFramework)]
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Accept_WithTargetSocket_ReuseAfterDisconnect_Success(bool reuseSocket)
{
if (!SupportsAcceptIntoExistingSocket)
return;
// APM mode fails currently. Issue: #22764
if (typeof(T) == typeof(SocketHelperApm))
return;
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listener.BindToAnonymousPort(IPAddress.Loopback);
listener.Listen(1);
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Task<Socket> acceptTask = AcceptAsync(listener, server);
client.Connect(IPAddress.Loopback, port);
Socket accepted = await acceptTask;
Assert.Same(server, accepted);
Assert.True(accepted.Connected);
}
server.Disconnect(reuseSocket);
Assert.False(server.Connected);
if (reuseSocket)
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Task<Socket> acceptTask = AcceptAsync(listener, server);
client.Connect(IPAddress.Loopback, port);
Socket accepted = await acceptTask;
Assert.Same(server, accepted);
Assert.True(accepted.Connected);
}
}
else
{
SocketException se = await Assert.ThrowsAsync<SocketException>(() => AcceptAsync(listener, server));
Assert.Equal(SocketError.InvalidArgument, se.SocketErrorCode);
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
public void Accept_WithAlreadyBoundTargetSocket_Fails()
{
if (!SupportsAcceptIntoExistingSocket)
return;
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listener.BindToAnonymousPort(IPAddress.Loopback);
listener.Listen(1);
server.BindToAnonymousPort(IPAddress.Loopback);
Assert.Throws<InvalidOperationException>(() => { AcceptAsync(listener, server); });
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
public async Task Accept_WithInUseTargetSocket_Fails()
{
if (!SupportsAcceptIntoExistingSocket)
return;
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listener.BindToAnonymousPort(IPAddress.Loopback);
listener.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listener, server);
client.Connect(IPAddress.Loopback, port);
Socket accepted = await acceptTask;
Assert.Same(server, accepted);
Assert.True(accepted.Connected);
Assert.Throws<InvalidOperationException>(() => { AcceptAsync(listener, server); });
}
}
[Fact]
public async Task AcceptAsync_MultipleAcceptsThenDispose_AcceptsThrowAfterDispose()
{
if (UsesSync)
{
return;
}
for (int i = 0; i < 100; i++)
{
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(2);
Task accept1 = AcceptAsync(listener);
Task accept2 = AcceptAsync(listener);
listener.Dispose();
await Assert.ThrowsAnyAsync<Exception>(() => accept1);
await Assert.ThrowsAnyAsync<Exception>(() => accept2);
}
}
}
}
public sealed class AcceptSync : Accept<SocketHelperArraySync>
{
public AcceptSync(ITestOutputHelper output) : base(output) {}
}
public sealed class AcceptSyncForceNonBlocking : Accept<SocketHelperSyncForceNonBlocking>
{
public AcceptSyncForceNonBlocking(ITestOutputHelper output) : base(output) {}
}
public sealed class AcceptApm : Accept<SocketHelperApm>
{
public AcceptApm(ITestOutputHelper output) : base(output) {}
}
public sealed class AcceptTask : Accept<SocketHelperTask>
{
public AcceptTask(ITestOutputHelper output) : base(output) {}
}
public sealed class AcceptEap : Accept<SocketHelperEap>
{
public AcceptEap(ITestOutputHelper output) : base(output) {}
}
}
| |
using System;
using Mozilla.NUniversalCharDet.Prober;
using System.ComponentModel.Composition;
namespace Mozilla.NUniversalCharDet
{
/// <summary>
/// Description of UniversalDetector.
/// </summary>
public class UniversalDetector
{
////////////////////////////////////////////////////////////////
// constants
////////////////////////////////////////////////////////////////
public static float SHORTCUT_THRESHOLD = 0.95f;
public static float MINIMUM_THRESHOLD = 0.20f;
////////////////////////////////////////////////////////////////
// inner types
////////////////////////////////////////////////////////////////
public enum InputState
{
PURE_ASCII,
ESC_ASCII,
HIGHBYTE
}
////////////////////////////////////////////////////////////////
// fields
////////////////////////////////////////////////////////////////
private InputState inputState;
private bool done;
private bool start;
private bool gotData;
private byte lastChar;
private string detectedCharset;
private CharsetProber[] probers;
private CharsetProber escCharsetProber;
private ICharsetListener listener;
////////////////////////////////////////////////////////////////
// methods
////////////////////////////////////////////////////////////////
/**
* @param listener a listener object that is notified of
* the detected encocoding. Can be null.
*/
public UniversalDetector(ICharsetListener listener)
{
this.listener = listener;
this.escCharsetProber = null;
this.probers = new CharsetProber[3];
for (int i = 0; i < this.probers.Length; ++i)
{
this.probers[i] = null;
}
Reset();
}
public bool IsDone()
{
return this.done;
}
/**
* @return The detected encoding is returned. If the detector couldn't
* determine what encoding was used, null is returned.
*/
public string GetDetectedCharset()
{
return this.detectedCharset;
}
public void SetListener(ICharsetListener listener)
{
this.listener = listener;
}
public ICharsetListener GetListener()
{
return this.listener;
}
public void HandleData(byte[] buf, int offset, int length)
{
if (this.done)
{
return;
}
if (length > 0)
{
this.gotData = true;
}
if (this.start)
{
this.start = false;
if (length > 3)
{
int b1 = buf[offset] & 0xFF;
int b2 = buf[offset + 1] & 0xFF;
int b3 = buf[offset + 2] & 0xFF;
int b4 = buf[offset + 3] & 0xFF;
switch (b1)
{
case 0xEF:
if (b2 == 0xBB && b3 == 0xBF)
{
this.detectedCharset = Constants.CHARSET_UTF_8;
}
break;
case 0xFE:
if (b2 == 0xFF && b3 == 0x00 && b4 == 0x00)
{
this.detectedCharset = Constants.CHARSET_X_ISO_10646_UCS_4_3412;
}
else if (b2 == 0xFF)
{
this.detectedCharset = Constants.CHARSET_UTF_16BE;
}
break;
case 0x00:
if (b2 == 0x00 && b3 == 0xFE && b4 == 0xFF)
{
this.detectedCharset = Constants.CHARSET_UTF_32BE;
}
else if (b2 == 0x00 && b3 == 0xFF && b4 == 0xFE)
{
this.detectedCharset = Constants.CHARSET_X_ISO_10646_UCS_4_2143;
}
break;
case 0xFF:
if (b2 == 0xFE && b3 == 0x00 && b4 == 0x00)
{
this.detectedCharset = Constants.CHARSET_UTF_32LE;
}
else if (b2 == 0xFE)
{
this.detectedCharset = Constants.CHARSET_UTF_16LE;
}
break;
} // swich end
if (this.detectedCharset != null)
{
this.done = true;
return;
}
}
} // if (start) end
int maxPos = offset + length;
for (int i = offset; i < maxPos; ++i)
{
int c = buf[i] & 0xFF;
if ((c & 0x80) != 0 && c != 0xA0)
{
if (this.inputState != InputState.HIGHBYTE)
{
this.inputState = InputState.HIGHBYTE;
if (this.escCharsetProber != null)
{
this.escCharsetProber = null;
}
if (this.probers[0] == null)
{
this.probers[0] = new MBCSGroupProber();
}
if (this.probers[1] == null)
{
this.probers[1] = new SBCSGroupProber();
}
if (this.probers[2] == null)
{
this.probers[2] = new Latin1Prober();
}
}
}
else
{
if (this.inputState == InputState.PURE_ASCII &&
(c == 0x1B || (c == 0x7B && this.lastChar == 0x7E)))
{
this.inputState = InputState.ESC_ASCII;
}
this.lastChar = buf[i];
}
} // for end
CharsetProber.ProbingState st;
if (this.inputState == InputState.ESC_ASCII)
{
if (this.escCharsetProber == null)
{
this.escCharsetProber = new EscCharsetProber();
}
st = this.escCharsetProber.handleData(buf, offset, length);
if (st == CharsetProber.ProbingState.FOUND_IT)
{
this.done = true;
this.detectedCharset = this.escCharsetProber.getCharSetName();
}
}
else if (this.inputState == InputState.HIGHBYTE)
{
for (int i = 0; i < this.probers.Length; ++i)
{
st = this.probers[i].handleData(buf, offset, length);
if (st == CharsetProber.ProbingState.FOUND_IT)
{
this.done = true;
this.detectedCharset = this.probers[i].getCharSetName();
return;
}
}
}
else
{ // pure ascii
// do nothing
}
}
public void DataEnd()
{
if (!this.gotData)
{
return;
}
if (this.detectedCharset != null)
{
this.done = true;
if (this.listener != null)
{
this.listener.Report(this.detectedCharset);
}
return;
}
if (this.inputState == InputState.HIGHBYTE)
{
float proberConfidence;
float maxProberConfidence = 0.0f;
int maxProber = 0;
for (int i = 0; i < this.probers.Length; ++i)
{
proberConfidence = this.probers[i].getConfidence();
if (proberConfidence > maxProberConfidence)
{
maxProberConfidence = proberConfidence;
maxProber = i;
}
}
if (maxProberConfidence > MINIMUM_THRESHOLD)
{
this.detectedCharset = this.probers[maxProber].getCharSetName();
if (this.listener != null)
{
this.listener.Report(this.detectedCharset);
}
}
}
else if (this.inputState == InputState.ESC_ASCII)
{
// do nothing
}
else
{
// do nothing
}
}
public void Reset()
{
this.done = false;
this.start = true;
this.detectedCharset = null;
this.gotData = false;
this.inputState = InputState.PURE_ASCII;
this.lastChar = 0;
if (this.escCharsetProber != null)
{
this.escCharsetProber.reset();
}
for (int i = 0; i < this.probers.Length; ++i)
{
if (this.probers[i] != null)
{
this.probers[i].reset();
}
}
}
}
}
| |
/*
* 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 ec2-2015-04-15.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.EC2.Model
{
/// <summary>
/// Describes a Reserved Instance.
/// </summary>
public partial class ReservedInstances
{
private string _availabilityZone;
private CurrencyCodeValues _currencyCode;
private long? _duration;
private DateTime? _end;
private float? _fixedPrice;
private int? _instanceCount;
private Tenancy _instanceTenancy;
private InstanceType _instanceType;
private OfferingTypeValues _offeringType;
private RIProductDescription _productDescription;
private List<RecurringCharge> _recurringCharges = new List<RecurringCharge>();
private string _reservedInstancesId;
private DateTime? _start;
private ReservedInstanceState _state;
private List<Tag> _tags = new List<Tag>();
private float? _usagePrice;
/// <summary>
/// Gets and sets the property AvailabilityZone.
/// <para>
/// The Availability Zone in which the Reserved Instance can be used.
/// </para>
/// </summary>
public string AvailabilityZone
{
get { return this._availabilityZone; }
set { this._availabilityZone = value; }
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this._availabilityZone != null;
}
/// <summary>
/// Gets and sets the property CurrencyCode.
/// <para>
/// The currency of the Reserved Instance. It's specified using ISO 4217 standard currency
/// codes. At this time, the only supported currency is <code>USD</code>.
/// </para>
/// </summary>
public CurrencyCodeValues CurrencyCode
{
get { return this._currencyCode; }
set { this._currencyCode = value; }
}
// Check to see if CurrencyCode property is set
internal bool IsSetCurrencyCode()
{
return this._currencyCode != null;
}
/// <summary>
/// Gets and sets the property Duration.
/// <para>
/// The duration of the Reserved Instance, in seconds.
/// </para>
/// </summary>
public long Duration
{
get { return this._duration.GetValueOrDefault(); }
set { this._duration = value; }
}
// Check to see if Duration property is set
internal bool IsSetDuration()
{
return this._duration.HasValue;
}
/// <summary>
/// Gets and sets the property End.
/// <para>
/// The time when the Reserved Instance expires.
/// </para>
/// </summary>
public DateTime End
{
get { return this._end.GetValueOrDefault(); }
set { this._end = value; }
}
// Check to see if End property is set
internal bool IsSetEnd()
{
return this._end.HasValue;
}
/// <summary>
/// Gets and sets the property FixedPrice.
/// <para>
/// The purchase price of the Reserved Instance.
/// </para>
/// </summary>
public float FixedPrice
{
get { return this._fixedPrice.GetValueOrDefault(); }
set { this._fixedPrice = value; }
}
// Check to see if FixedPrice property is set
internal bool IsSetFixedPrice()
{
return this._fixedPrice.HasValue;
}
/// <summary>
/// Gets and sets the property InstanceCount.
/// <para>
/// The number of Reserved Instances purchased.
/// </para>
/// </summary>
public int InstanceCount
{
get { return this._instanceCount.GetValueOrDefault(); }
set { this._instanceCount = value; }
}
// Check to see if InstanceCount property is set
internal bool IsSetInstanceCount()
{
return this._instanceCount.HasValue;
}
/// <summary>
/// Gets and sets the property InstanceTenancy.
/// <para>
/// The tenancy of the reserved instance.
/// </para>
/// </summary>
public Tenancy InstanceTenancy
{
get { return this._instanceTenancy; }
set { this._instanceTenancy = value; }
}
// Check to see if InstanceTenancy property is set
internal bool IsSetInstanceTenancy()
{
return this._instanceTenancy != null;
}
/// <summary>
/// Gets and sets the property InstanceType.
/// <para>
/// The instance type on which the Reserved Instance can be used.
/// </para>
/// </summary>
public InstanceType InstanceType
{
get { return this._instanceType; }
set { this._instanceType = value; }
}
// Check to see if InstanceType property is set
internal bool IsSetInstanceType()
{
return this._instanceType != null;
}
/// <summary>
/// Gets and sets the property OfferingType.
/// <para>
/// The Reserved Instance offering type.
/// </para>
/// </summary>
public OfferingTypeValues OfferingType
{
get { return this._offeringType; }
set { this._offeringType = value; }
}
// Check to see if OfferingType property is set
internal bool IsSetOfferingType()
{
return this._offeringType != null;
}
/// <summary>
/// Gets and sets the property ProductDescription.
/// <para>
/// The Reserved Instance product platform description.
/// </para>
/// </summary>
public RIProductDescription ProductDescription
{
get { return this._productDescription; }
set { this._productDescription = value; }
}
// Check to see if ProductDescription property is set
internal bool IsSetProductDescription()
{
return this._productDescription != null;
}
/// <summary>
/// Gets and sets the property RecurringCharges.
/// <para>
/// The recurring charge tag assigned to the resource.
/// </para>
/// </summary>
public List<RecurringCharge> RecurringCharges
{
get { return this._recurringCharges; }
set { this._recurringCharges = value; }
}
// Check to see if RecurringCharges property is set
internal bool IsSetRecurringCharges()
{
return this._recurringCharges != null && this._recurringCharges.Count > 0;
}
/// <summary>
/// Gets and sets the property ReservedInstancesId.
/// <para>
/// The ID of the Reserved Instance.
/// </para>
/// </summary>
public string ReservedInstancesId
{
get { return this._reservedInstancesId; }
set { this._reservedInstancesId = value; }
}
// Check to see if ReservedInstancesId property is set
internal bool IsSetReservedInstancesId()
{
return this._reservedInstancesId != null;
}
/// <summary>
/// Gets and sets the property Start.
/// <para>
/// The date and time the Reserved Instance started.
/// </para>
/// </summary>
public DateTime Start
{
get { return this._start.GetValueOrDefault(); }
set { this._start = value; }
}
// Check to see if Start property is set
internal bool IsSetStart()
{
return this._start.HasValue;
}
/// <summary>
/// Gets and sets the property State.
/// <para>
/// The state of the Reserved Instance purchase.
/// </para>
/// </summary>
public ReservedInstanceState State
{
get { return this._state; }
set { this._state = value; }
}
// Check to see if State property is set
internal bool IsSetState()
{
return this._state != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// Any tags assigned to the resource.
/// </para>
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property UsagePrice.
/// <para>
/// The usage price of the Reserved Instance, per hour.
/// </para>
/// </summary>
public float UsagePrice
{
get { return this._usagePrice.GetValueOrDefault(); }
set { this._usagePrice = value; }
}
// Check to see if UsagePrice property is set
internal bool IsSetUsagePrice()
{
return this._usagePrice.HasValue;
}
}
}
| |
// 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 SysDebug = System.Diagnostics.Debug; // as Regex.Debug
using System.Collections.Generic;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Text.RegularExpressions
{
public partial class Regex
{
private const int CacheDictionarySwitchLimit = 10;
private static int s_cacheSize = 15;
// the cache of code and factories that are currently loaded:
// Dictionary for large cache
private static readonly Dictionary<CachedCodeEntryKey, CachedCodeEntry> s_cache = new Dictionary<CachedCodeEntryKey, CachedCodeEntry>(s_cacheSize);
// linked list for LRU and for small cache
private static int s_cacheCount = 0;
private static CachedCodeEntry s_cacheFirst;
private static CachedCodeEntry s_cacheLast;
public static int CacheSize
{
get
{
return s_cacheSize;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
lock (s_cache)
{
s_cacheSize = value; // not to allow other thread to change it while we use cache
while (s_cacheCount > s_cacheSize)
{
CachedCodeEntry last = s_cacheLast;
if (s_cacheCount >= CacheDictionarySwitchLimit)
{
SysDebug.Assert(s_cache.ContainsKey(last.Key));
s_cache.Remove(last.Key);
}
// update linked list:
s_cacheLast = last.Next;
if (last.Next != null)
{
SysDebug.Assert(s_cacheFirst != null);
SysDebug.Assert(s_cacheFirst != last);
SysDebug.Assert(last.Next.Previous == last);
last.Next.Previous = null;
}
else // last one removed
{
SysDebug.Assert(s_cacheFirst == last);
s_cacheFirst = null;
}
s_cacheCount--;
}
}
}
}
/// <summary>
/// Find cache based on options+pattern+culture and optionally add new cache if not found
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private CachedCodeEntry GetCachedCode(CachedCodeEntryKey key, bool isToAdd)
{
// to avoid lock:
CachedCodeEntry first = s_cacheFirst;
if (first?.Key == key)
return first;
if (s_cacheSize == 0)
return null;
return GetCachedCodeEntryInternal(key, isToAdd);
}
private CachedCodeEntry GetCachedCodeEntryInternal(CachedCodeEntryKey key, bool isToAdd)
{
lock (s_cache)
{
// first look for it in the cache and move it to the head
CachedCodeEntry entry = LookupCachedAndPromote(key);
// it wasn't in the cache, so we'll add a new one
if (entry == null && isToAdd && s_cacheSize != 0) // check cache size again in case it changed
{
entry = new CachedCodeEntry(key, capnames, capslist, _code, caps, capsize, _runnerref, _replref);
// put first in linked list:
if (s_cacheFirst != null)
{
SysDebug.Assert(s_cacheFirst.Next == null);
s_cacheFirst.Next = entry;
entry.Previous = s_cacheFirst;
}
s_cacheFirst = entry;
s_cacheCount++;
if (s_cacheCount >= CacheDictionarySwitchLimit)
{
if (s_cacheCount == CacheDictionarySwitchLimit)
FillCacheDictionary();
else
s_cache.Add(key, entry);
SysDebug.Assert(s_cacheCount == s_cache.Count);
}
// update last in linked list:
if (s_cacheLast == null)
{
s_cacheLast = entry;
}
else if (s_cacheCount > s_cacheSize) // remove last
{
CachedCodeEntry last = s_cacheLast;
if (s_cacheCount >= CacheDictionarySwitchLimit)
{
SysDebug.Assert(s_cache[last.Key] == s_cacheLast);
s_cache.Remove(last.Key);
}
SysDebug.Assert(last.Previous == null);
SysDebug.Assert(last.Next != null);
SysDebug.Assert(last.Next.Previous == last);
last.Next.Previous = null;
s_cacheLast = last.Next;
s_cacheCount--;
}
}
return entry;
}
}
private void FillCacheDictionary()
{
s_cache.Clear();
CachedCodeEntry next = s_cacheFirst;
while (next != null)
{
s_cache.Add(next.Key, next);
next = next.Previous;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] // Unprofitable inline - JIT overly pessimistic
private static bool TryGetCacheValue(CachedCodeEntryKey key, out CachedCodeEntry entry)
{
if (s_cacheCount >= CacheDictionarySwitchLimit)
{
SysDebug.Assert((s_cacheFirst != null && s_cacheLast != null && s_cache.Count > 0) ||
(s_cacheFirst == null && s_cacheLast == null && s_cache.Count == 0),
"Linked list and Dict should be synchronized");
return s_cache.TryGetValue(key, out entry);
}
return TryGetCacheValueSmall(key, out entry);
}
private static bool TryGetCacheValueSmall(CachedCodeEntryKey key, out CachedCodeEntry entry)
{
entry = s_cacheFirst?.Previous; // first already checked
while (entry != null)
{
if (entry.Key == key)
return true;
entry = entry.Previous;
}
return false;
}
private static CachedCodeEntry LookupCachedAndPromote(CachedCodeEntryKey key)
{
SysDebug.Assert(Monitor.IsEntered(s_cache));
if (s_cacheFirst?.Key == key) // again check this as could have been promoted by other thread
return s_cacheFirst;
if (TryGetCacheValue(key, out CachedCodeEntry entry))
{
// promote:
SysDebug.Assert(s_cacheFirst != entry, "key should not get s_livecode_first");
SysDebug.Assert(s_cacheFirst != null, "as Dict has at least one");
SysDebug.Assert(s_cacheFirst.Next == null);
SysDebug.Assert(s_cacheFirst.Previous != null);
SysDebug.Assert(entry.Next != null, "not first so Next should exist");
SysDebug.Assert(entry.Next.Previous == entry);
if (s_cacheLast == entry)
{
SysDebug.Assert(entry.Previous == null, "last");
s_cacheLast = entry.Next;
}
else
{
SysDebug.Assert(entry.Previous != null, "in middle");
SysDebug.Assert(entry.Previous.Next == entry);
entry.Previous.Next = entry.Next;
}
entry.Next.Previous = entry.Previous;
s_cacheFirst.Next = entry;
entry.Previous = s_cacheFirst;
entry.Next = null;
s_cacheFirst = entry;
}
return entry;
}
/// <summary>
/// Used as a key for CacheCodeEntry
/// </summary>
internal readonly struct CachedCodeEntryKey : IEquatable<CachedCodeEntryKey>
{
private readonly RegexOptions _options;
private readonly string _cultureKey;
private readonly string _pattern;
public CachedCodeEntryKey(RegexOptions options, string cultureKey, string pattern)
{
SysDebug.Assert(cultureKey != null, "Culture must be provided");
SysDebug.Assert(pattern != null, "Pattern must be provided");
_options = options;
_cultureKey = cultureKey;
_pattern = pattern;
}
public override bool Equals(object obj)
{
return obj is CachedCodeEntryKey && Equals((CachedCodeEntryKey)obj);
}
public bool Equals(CachedCodeEntryKey other)
{
return _pattern.Equals(other._pattern) && _options == other._options && _cultureKey.Equals(other._cultureKey);
}
public static bool operator ==(CachedCodeEntryKey left, CachedCodeEntryKey right)
{
return left.Equals(right);
}
public static bool operator !=(CachedCodeEntryKey left, CachedCodeEntryKey right)
{
return !left.Equals(right);
}
public override int GetHashCode()
{
return ((int)_options) ^ _cultureKey.GetHashCode() ^ _pattern.GetHashCode();
}
}
/// <summary>
/// Used to cache byte codes
/// </summary>
internal sealed class CachedCodeEntry
{
public CachedCodeEntry Next;
public CachedCodeEntry Previous;
public readonly CachedCodeEntryKey Key;
public RegexCode Code;
public readonly Hashtable Caps;
public readonly Hashtable Capnames;
public readonly string[] Capslist;
#if FEATURE_COMPILED
public RegexRunnerFactory Factory;
#endif
public readonly int Capsize;
public readonly ExclusiveReference Runnerref;
public readonly WeakReference<RegexReplacement> ReplRef;
public CachedCodeEntry(CachedCodeEntryKey key, Hashtable capnames, string[] capslist, RegexCode code,
Hashtable caps, int capsize, ExclusiveReference runner, WeakReference<RegexReplacement> replref)
{
Key = key;
Capnames = capnames;
Capslist = capslist;
Code = code;
Caps = caps;
Capsize = capsize;
Runnerref = runner;
ReplRef = replref;
}
#if FEATURE_COMPILED
public void AddCompiled(RegexRunnerFactory factory)
{
Factory = factory;
Code = null;
}
#endif
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using NUnit.Common;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnitLite
{
public class TextUI
{
public ExtendedTextWriter Writer { get; }
private readonly TextReader _reader;
private readonly NUnitLiteOptions _options;
private readonly bool _displayBeforeTest;
private readonly bool _displayAfterTest;
private readonly bool _displayBeforeOutput;
#region Constructor
public TextUI(ExtendedTextWriter writer, TextReader reader, NUnitLiteOptions options)
{
Writer = writer;
_reader = reader;
_options = options;
string labelsOption = options.DisplayTestLabels?.ToUpperInvariant() ?? "ON";
_displayBeforeTest = labelsOption == "ALL" || labelsOption == "BEFORE";
_displayAfterTest = labelsOption == "AFTER";
_displayBeforeOutput = _displayBeforeTest || _displayAfterTest || labelsOption == "ON";
}
#endregion
#region Public Methods
#region DisplayHeader
/// <summary>
/// Writes the header.
/// </summary>
public void DisplayHeader()
{
Assembly executingAssembly = GetType().GetTypeInfo().Assembly;
AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly);
Version version = assemblyName.Version;
string copyright = "Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt";
string build = "";
var copyrightAttr = executingAssembly.GetCustomAttribute<AssemblyCopyrightAttribute>();
if (copyrightAttr != null)
copyright = copyrightAttr.Copyright;
var configAttr = executingAssembly.GetCustomAttribute<AssemblyConfigurationAttribute>();
if (configAttr != null)
build = string.Format("({0})", configAttr.Configuration);
WriteHeader(String.Format("NUnitLite {0} {1}", version.ToString(3), build));
WriteSubHeader(copyright);
Writer.WriteLine();
}
#endregion
#region DisplayTestFiles
public void DisplayTestFiles(IEnumerable<string> testFiles)
{
WriteSectionHeader("Test Files");
foreach (string testFile in testFiles)
Writer.WriteLine(ColorStyle.Default, " " + testFile);
Writer.WriteLine();
}
#endregion
#region DisplayHelp
public void DisplayHelp()
{
WriteHeader("Usage: NUNITLITE-RUNNER assembly [options]");
WriteHeader(" USER-EXECUTABLE [options]");
Writer.WriteLine();
WriteHelpLine("Runs a set of NUnitLite tests from the console.");
Writer.WriteLine();
WriteSectionHeader("Assembly:");
WriteHelpLine(" File name or path of the assembly from which to execute tests. Required");
WriteHelpLine(" when using the nunitlite-runner executable to run the tests. Not allowed");
WriteHelpLine(" when running a self-executing user test assembly.");
Writer.WriteLine();
WriteSectionHeader("Options:");
using (var sw = new StringWriter())
{
_options.WriteOptionDescriptions(sw);
Writer.Write(ColorStyle.Help, sw.ToString());
}
WriteSectionHeader("Notes:");
WriteHelpLine(" * File names may be listed by themselves, with a relative path or ");
WriteHelpLine(" using an absolute path. Any relative path is based on the current ");
WriteHelpLine(" directory.");
Writer.WriteLine();
WriteHelpLine(" * On Windows, options may be prefixed by a '/' character if desired");
Writer.WriteLine();
WriteHelpLine(" * Options that take values may use an equal sign or a colon");
WriteHelpLine(" to separate the option from its value.");
Writer.WriteLine();
WriteHelpLine(" * Several options that specify processing of XML output take");
WriteHelpLine(" an output specification as a value. A SPEC may take one of");
WriteHelpLine(" the following forms:");
WriteHelpLine(" --OPTION:filename");
WriteHelpLine(" --OPTION:filename;format=formatname");
Writer.WriteLine();
WriteHelpLine(" The --result option may use any of the following formats:");
WriteHelpLine(" nunit3 - the native XML format for NUnit 3");
WriteHelpLine(" nunit2 - legacy XML format used by earlier releases of NUnit");
Writer.WriteLine();
WriteHelpLine(" The --explore option may use any of the following formats:");
WriteHelpLine(" nunit3 - the native XML format for NUnit 3");
WriteHelpLine(" cases - a text file listing the full names of all test cases.");
WriteHelpLine(" If --explore is used without any specification following, a list of");
WriteHelpLine(" test cases is output to the console.");
Writer.WriteLine();
}
#endregion
#region DisplayRuntimeEnvironment
/// <summary>
/// Displays info about the runtime environment.
/// </summary>
public void DisplayRuntimeEnvironment()
{
WriteSectionHeader("Runtime Environment");
#if NETSTANDARD2_0
Writer.WriteLabelLine(" OS Version: ", System.Runtime.InteropServices.RuntimeInformation.OSDescription);
#else
Writer.WriteLabelLine(" OS Version: ", OSPlatform.CurrentPlatform);
#endif
Writer.WriteLabelLine(" CLR Version: ", Environment.Version);
Writer.WriteLine();
}
#endregion
#region Test Discovery Report
public void DisplayDiscoveryReport(TimeStamp startTime, TimeStamp endTime)
{
WriteSectionHeader("Test Discovery");
foreach (string filter in _options.PreFilters)
Writer.WriteLabelLine(" Pre-Filter: ", filter);
Writer.WriteLabelLine(" Start time: ", startTime.DateTime.ToString("u"));
Writer.WriteLabelLine(" End time: ", endTime.DateTime.ToString("u"));
double elapsedSeconds = TimeStamp.TicksToSeconds(endTime.Ticks - startTime.Ticks);
Writer.WriteLabelLine(" Duration: ", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000} seconds", elapsedSeconds));
Writer.WriteLine();
}
#endregion
#region DisplayTestFilters
public void DisplayTestFilters()
{
if (_options.TestList.Count > 0 || _options.WhereClauseSpecified)
{
WriteSectionHeader("Test Filters");
foreach (string testName in _options.TestList)
Writer.WriteLabelLine(" Test: ", testName);
if (_options.WhereClauseSpecified)
Writer.WriteLabelLine(" Where: ", _options.WhereClause.Trim());
Writer.WriteLine();
}
}
#endregion
#region DisplayRunSettings
public void DisplayRunSettings()
{
WriteSectionHeader("Run Settings");
if (_options.DefaultTimeout >= 0)
Writer.WriteLabelLine(" Default timeout: ", _options.DefaultTimeout);
Writer.WriteLabelLine(
" Number of Test Workers: ",
_options.NumberOfTestWorkers >= 0
? _options.NumberOfTestWorkers
: Math.Max(Environment.ProcessorCount, 2));
Writer.WriteLabelLine(" Work Directory: ", _options.WorkDirectory ?? Directory.GetCurrentDirectory());
Writer.WriteLabelLine(" Internal Trace: ", _options.InternalTraceLevel ?? "Off");
if (_options.TeamCity)
Writer.WriteLine(ColorStyle.Value, " Display TeamCity Service Messages");
Writer.WriteLine();
}
#endregion
#region TestStarted
public void TestStarted(ITest test)
{
if (_displayBeforeTest && !test.IsSuite)
WriteLabelLine(test.FullName);
}
#endregion
#region TestFinished
private bool _testCreatedOutput = false;
private bool _needsNewLine = false;
public void TestFinished(ITestResult result)
{
if (result.Output.Length > 0)
{
if (_displayBeforeOutput)
WriteLabelLine(result.Test.FullName);
WriteOutput(result.Output);
if (!result.Output.EndsWith("\n", StringComparison.Ordinal))
Writer.WriteLine();
}
if (!result.Test.IsSuite)
{
if (_displayAfterTest)
WriteLabelLineAfterTest(result.Test.FullName, result.ResultState);
}
if (result.Test is TestAssembly && _testCreatedOutput)
{
Writer.WriteLine();
_testCreatedOutput = false;
}
}
#endregion
#region TestOutput
public void TestOutput(TestOutput output)
{
if (_displayBeforeOutput && output.TestName != null)
WriteLabelLine(output.TestName);
WriteOutput(output.Stream == "Error" ? ColorStyle.Error : ColorStyle.Output, output.Text);
}
#endregion
#region WaitForUser
public void WaitForUser(string message)
{
// Ignore if we don't have a TextReader
if (_reader != null)
{
Writer.WriteLine(ColorStyle.Label, message);
_reader.ReadLine();
}
}
#endregion
#region Test Result Reports
#region DisplaySummaryReport
public void DisplaySummaryReport(ResultSummary summary)
{
var status = summary.ResultState.Status;
var overallResult = status.ToString();
if (overallResult == "Skipped")
overallResult = "Warning";
ColorStyle overallStyle = status == TestStatus.Passed
? ColorStyle.Pass
: status == TestStatus.Failed
? ColorStyle.Failure
: status == TestStatus.Skipped
? ColorStyle.Warning
: ColorStyle.Output;
if (_testCreatedOutput)
Writer.WriteLine();
WriteSectionHeader("Test Run Summary");
Writer.WriteLabelLine(" Overall result: ", overallResult, overallStyle);
WriteSummaryCount(" Test Count: ", summary.TestCount);
WriteSummaryCount(", Passed: ", summary.PassCount);
WriteSummaryCount(", Failed: ", summary.FailedCount, ColorStyle.Failure);
WriteSummaryCount(", Warnings: ", summary.WarningCount, ColorStyle.Warning);
WriteSummaryCount(", Inconclusive: ", summary.InconclusiveCount);
WriteSummaryCount(", Skipped: ", summary.TotalSkipCount);
Writer.WriteLine();
if (summary.FailedCount > 0)
{
WriteSummaryCount(" Failed Tests - Failures: ", summary.FailureCount, ColorStyle.Failure);
WriteSummaryCount(", Errors: ", summary.ErrorCount, ColorStyle.Error);
WriteSummaryCount(", Invalid: ", summary.InvalidCount, ColorStyle.Error);
Writer.WriteLine();
}
if (summary.TotalSkipCount > 0)
{
WriteSummaryCount(" Skipped Tests - Ignored: ", summary.IgnoreCount, ColorStyle.Warning);
WriteSummaryCount(", Explicit: ", summary.ExplicitCount);
WriteSummaryCount(", Other: ", summary.SkipCount);
Writer.WriteLine();
}
Writer.WriteLabelLine(" Start time: ", summary.StartTime.ToString("u"));
Writer.WriteLabelLine(" End time: ", summary.EndTime.ToString("u"));
Writer.WriteLabelLine(" Duration: ", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000} seconds", summary.Duration));
Writer.WriteLine();
}
private void WriteSummaryCount(string label, int count)
{
Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture));
}
private void WriteSummaryCount(string label, int count, ColorStyle color)
{
Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture), count > 0 ? color : ColorStyle.Value);
}
#endregion
#region DisplayErrorsAndFailuresReport
public void DisplayErrorsFailuresAndWarningsReport(ITestResult result)
{
_reportIndex = 0;
WriteSectionHeader("Errors, Failures and Warnings");
DisplayErrorsFailuresAndWarnings(result);
Writer.WriteLine();
if (_options.StopOnError)
{
Writer.WriteLine(ColorStyle.Failure, "Execution terminated after first error");
Writer.WriteLine();
}
}
#endregion
#region DisplayNotRunReport
public void DisplayNotRunReport(ITestResult result)
{
_reportIndex = 0;
WriteSectionHeader("Tests Not Run");
DisplayNotRunResults(result);
Writer.WriteLine();
}
#endregion
#region DisplayFullReport
#if FULL // Not currently used, but may be reactivated
/// <summary>
/// Prints a full report of all results
/// </summary>
public void DisplayFullReport(ITestResult result)
{
WriteLine(ColorStyle.SectionHeader, "All Test Results -");
_writer.WriteLine();
DisplayAllResults(result, " ");
_writer.WriteLine();
}
#endif
#endregion
#endregion
#region DisplayWarning
public void DisplayWarning(string text)
{
Writer.WriteLine(ColorStyle.Warning, text);
}
#endregion
#region DisplayError
public void DisplayError(string text)
{
Writer.WriteLine(ColorStyle.Error, text);
}
#endregion
#region DisplayErrors
public void DisplayErrors(IList<string> messages)
{
foreach (string message in messages)
DisplayError(message);
}
#endregion
#endregion
#region Helper Methods
private void DisplayErrorsFailuresAndWarnings(ITestResult result)
{
bool display =
result.ResultState.Status == TestStatus.Failed ||
result.ResultState.Status == TestStatus.Warning;
if (result.Test.IsSuite)
{
if (display)
{
var suite = result.Test as TestSuite;
var site = result.ResultState.Site;
if (suite.TestType == "Theory" || site == FailureSite.SetUp || site == FailureSite.TearDown)
DisplayTestResult(result);
if (site == FailureSite.SetUp) return;
}
foreach (ITestResult childResult in result.Children)
DisplayErrorsFailuresAndWarnings(childResult);
}
else if (display)
DisplayTestResult(result);
}
private void DisplayNotRunResults(ITestResult result)
{
if (result.HasChildren)
foreach (ITestResult childResult in result.Children)
DisplayNotRunResults(childResult);
else if (result.ResultState.Status == TestStatus.Skipped)
DisplayTestResult(result);
}
private static readonly char[] TRIM_CHARS = new char[] { '\r', '\n' };
private int _reportIndex;
private void DisplayTestResult(ITestResult result)
{
ResultState resultState = result.ResultState;
string fullName = result.FullName;
string message = result.Message;
string stackTrace = result.StackTrace;
string reportId = (++_reportIndex).ToString();
int numAsserts = result.AssertionResults.Count;
if (numAsserts > 0)
{
int assertionCounter = 0;
string assertId = reportId;
foreach (var assertion in result.AssertionResults)
{
if (numAsserts > 1)
assertId = string.Format("{0}-{1}", reportId, ++assertionCounter);
ColorStyle style = GetColorStyle(resultState);
string status = assertion.Status.ToString();
DisplayTestResult(style, assertId, status, fullName, assertion.Message, assertion.StackTrace);
}
}
else
{
ColorStyle style = GetColorStyle(resultState);
string status = GetResultStatus(resultState);
DisplayTestResult(style, reportId, status, fullName, message, stackTrace);
}
}
private void DisplayTestResult(ColorStyle style, string prefix, string status, string fullName, string message, string stackTrace)
{
Writer.WriteLine();
Writer.WriteLine(
style, string.Format("{0}) {1} : {2}", prefix, status, fullName));
if (!string.IsNullOrEmpty(message))
Writer.WriteLine(style, message.TrimEnd(TRIM_CHARS));
if (!string.IsNullOrEmpty(stackTrace))
Writer.WriteLine(style, stackTrace.TrimEnd(TRIM_CHARS));
}
private static ColorStyle GetColorStyle(ResultState resultState)
{
ColorStyle style = ColorStyle.Output;
switch (resultState.Status)
{
case TestStatus.Failed:
style = ColorStyle.Failure;
break;
case TestStatus.Warning:
style = ColorStyle.Warning;
break;
case TestStatus.Skipped:
style = resultState.Label == "Ignored" ? ColorStyle.Warning : ColorStyle.Output;
break;
case TestStatus.Passed:
style = ColorStyle.Pass;
break;
}
return style;
}
private static string GetResultStatus(ResultState resultState)
{
string status = resultState.Label;
if (string.IsNullOrEmpty(status))
status = resultState.Status.ToString();
if (status == "Failed" || status == "Error")
{
var site = resultState.Site.ToString();
if (site == "SetUp" || site == "TearDown")
status = site + " " + status;
}
return status;
}
#if FULL
private void DisplayAllResults(ITestResult result, string indent)
{
string status = null;
ColorStyle style = ColorStyle.Output;
switch (result.ResultState.Status)
{
case TestStatus.Failed:
status = "FAIL";
style = ColorStyle.Failure;
break;
case TestStatus.Skipped:
if (result.ResultState.Label == "Ignored")
{
status = "IGN ";
style = ColorStyle.Warning;
}
else
{
status = "SKIP";
style = ColorStyle.Output;
}
break;
case TestStatus.Inconclusive:
status = "INC ";
style = ColorStyle.Output;
break;
case TestStatus.Passed:
status = "OK ";
style = ColorStyle.Pass;
break;
}
WriteLine(style, status + indent + result.Name);
if (result.HasChildren)
foreach (ITestResult childResult in result.Children)
PrintAllResults(childResult, indent + " ");
}
#endif
private void WriteHeader(string text)
{
Writer.WriteLine(ColorStyle.Header, text);
}
private void WriteSubHeader(string text)
{
Writer.WriteLine(ColorStyle.SubHeader, text);
}
private void WriteSectionHeader(string text)
{
Writer.WriteLine(ColorStyle.SectionHeader, text);
}
private void WriteHelpLine(string text)
{
Writer.WriteLine(ColorStyle.Help, text);
}
private string _currentLabel;
private void WriteLabelLine(string label)
{
if (label != _currentLabel)
{
WriteNewLineIfNeeded();
Writer.WriteLine(ColorStyle.SectionHeader, "=> " + label);
_testCreatedOutput = true;
_currentLabel = label;
}
}
private void WriteLabelLineAfterTest(string label, ResultState resultState)
{
WriteNewLineIfNeeded();
string status = string.IsNullOrEmpty(resultState.Label)
? resultState.Status.ToString()
: resultState.Label;
Writer.Write(GetColorForResultStatus(status), status);
Writer.WriteLine(ColorStyle.SectionHeader, " => " + label);
_currentLabel = label;
}
private void WriteNewLineIfNeeded()
{
if (_needsNewLine)
{
Writer.WriteLine();
_needsNewLine = false;
}
}
private void WriteOutput(string text)
{
WriteOutput(ColorStyle.Output, text);
}
private void WriteOutput(ColorStyle color, string text)
{
Writer.Write(color, text);
_testCreatedOutput = true;
_needsNewLine = !text.EndsWith("\n", StringComparison.Ordinal);
}
private static ColorStyle GetColorForResultStatus(string status)
{
switch (status)
{
case "Passed":
return ColorStyle.Pass;
case "Failed":
return ColorStyle.Failure;
case "Error":
case "Invalid":
case "Cancelled":
return ColorStyle.Error;
case "Warning":
case "Ignored":
return ColorStyle.Warning;
default:
return ColorStyle.Output;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
public partial struct ImmutableArray<T>
{
/// <summary>
/// A writable array accessor that can be converted into an <see cref="ImmutableArray{T}"/>
/// instance without allocating memory.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))]
public sealed class Builder : IList<T>, IReadOnlyList<T>
{
/// <summary>
/// The backing array for the builder.
/// </summary>
private T[] _elements;
/// <summary>
/// The number of initialized elements in the array.
/// </summary>
private int _count;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="capacity">The initial capacity of the internal array.</param>
internal Builder(int capacity)
{
Requires.Range(capacity >= 0, nameof(capacity));
_elements = new T[capacity];
_count = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
internal Builder()
: this(8)
{
}
/// <summary>
/// Get and sets the length of the internal array. When set the internal array is
/// reallocated to the given capacity if it is not already the specified length.
/// </summary>
public int Capacity
{
get { return _elements.Length; }
set
{
if (value < _count)
{
throw new ArgumentException(SR.CapacityMustBeGreaterThanOrEqualToCount, paramName: nameof(value));
}
if (value != _elements.Length)
{
if (value > 0)
{
var temp = new T[value];
if (_count > 0)
{
Array.Copy(_elements, 0, temp, 0, _count);
}
_elements = temp;
}
else
{
_elements = ImmutableArray<T>.Empty.array;
}
}
}
}
/// <summary>
/// Gets or sets the length of the builder.
/// </summary>
/// <remarks>
/// If the value is decreased, the array contents are truncated.
/// If the value is increased, the added elements are initialized to the default value of type <typeparamref name="T"/>.
/// </remarks>
public int Count
{
get
{
return _count;
}
set
{
Requires.Range(value >= 0, nameof(value));
if (value < _count)
{
// truncation mode
// Clear the elements of the elements that are effectively removed.
// PERF: Array.Clear works well for big arrays,
// but may have too much overhead with small ones (which is the common case here)
if (_count - value > 64)
{
Array.Clear(_elements, value, _count - value);
}
else
{
for (int i = value; i < this.Count; i++)
{
_elements[i] = default(T);
}
}
}
else if (value > _count)
{
// expansion
this.EnsureCapacity(value);
}
_count = value;
}
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// </exception>
public T this[int index]
{
get
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
return _elements[index];
}
set
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
_elements[index] = value;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Returns an immutable copy of the current contents of this collection.
/// </summary>
/// <returns>An immutable array.</returns>
public ImmutableArray<T> ToImmutable()
{
if (Count == 0)
{
return Empty;
}
return new ImmutableArray<T>(this.ToArray());
}
/// <summary>
/// Extracts the internal array as an <see cref="ImmutableArray{T}"/> and replaces it
/// with a zero length array.
/// </summary>
/// <exception cref="InvalidOperationException">When <see cref="ImmutableArray{T}.Builder.Count"/> doesn't
/// equal <see cref="ImmutableArray{T}.Builder.Capacity"/>.</exception>
public ImmutableArray<T> MoveToImmutable()
{
if (Capacity != Count)
{
throw new InvalidOperationException(SR.CapacityMustEqualCountOnMove);
}
T[] temp = _elements;
_elements = ImmutableArray<T>.Empty.array;
_count = 0;
return new ImmutableArray<T>(temp);
}
/// <summary>
/// Removes all items from the <see cref="ICollection{T}"/>.
/// </summary>
public void Clear()
{
this.Count = 0;
}
/// <summary>
/// Inserts an item to the <see cref="IList{T}"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="IList{T}"/>.</param>
public void Insert(int index, T item)
{
Requires.Range(index >= 0 && index <= this.Count, nameof(index));
this.EnsureCapacity(this.Count + 1);
if (index < this.Count)
{
Array.Copy(_elements, index, _elements, index + 1, this.Count - index);
}
_count++;
_elements[index] = item;
}
/// <summary>
/// Adds an item to the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param>
public void Add(T item)
{
this.EnsureCapacity(this.Count + 1);
_elements[_count++] = item;
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(IEnumerable<T> items)
{
Requires.NotNull(items, nameof(items));
int count;
if (items.TryGetCount(out count))
{
this.EnsureCapacity(this.Count + count);
}
foreach (var item in items)
{
this.Add(item);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(params T[] items)
{
Requires.NotNull(items, nameof(items));
var offset = this.Count;
this.Count += items.Length;
Array.Copy(items, 0, _elements, offset, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(TDerived[] items) where TDerived : T
{
Requires.NotNull(items, nameof(items));
var offset = this.Count;
this.Count += items.Length;
Array.Copy(items, 0, _elements, offset, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(T[] items, int length)
{
Requires.NotNull(items, nameof(items));
Requires.Range(length >= 0 && length <= items.Length, nameof(length));
var offset = this.Count;
this.Count += length;
Array.Copy(items, 0, _elements, offset, length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(ImmutableArray<T> items)
{
this.AddRange(items, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(ImmutableArray<T> items, int length)
{
Requires.Range(length >= 0, nameof(length));
if (items.array != null)
{
this.AddRange(items.array, length);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T
{
if (items.array != null)
{
this.AddRange(items.array);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(Builder items)
{
Requires.NotNull(items, nameof(items));
this.AddRange(items._elements, items.Count);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T
{
Requires.NotNull(items, nameof(items));
this.AddRange(items._elements, items.Count);
}
/// <summary>
/// Removes the specified element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>A value indicating whether the specified element was found and removed from the collection.</returns>
public bool Remove(T element)
{
int index = this.IndexOf(element);
if (index >= 0)
{
this.RemoveAt(index);
return true;
}
return false;
}
/// <summary>
/// Removes the <see cref="IList{T}"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
Requires.Range(index >= 0 && index < this.Count, nameof(index));
if (index < this.Count - 1)
{
Array.Copy(_elements, index + 1, _elements, index, this.Count - index - 1);
}
this.Count--;
}
/// <summary>
/// Determines whether the <see cref="ICollection{T}"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false.
/// </returns>
public bool Contains(T item)
{
return this.IndexOf(item) >= 0;
}
/// <summary>
/// Creates a new array with the current contents of this Builder.
/// </summary>
public T[] ToArray()
{
T[] result = new T[this.Count];
Array.Copy(_elements, 0, result, 0, this.Count);
return result;
}
/// <summary>
/// Copies the current contents to the specified array.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="index">The starting index of the target array.</param>
public void CopyTo(T[] array, int index)
{
Requires.NotNull(array, nameof(array));
Requires.Range(index >= 0 && index + this.Count <= array.Length, nameof(index));
Array.Copy(_elements, 0, array, index, this.Count);
}
/// <summary>
/// Resizes the array to accommodate the specified capacity requirement.
/// </summary>
/// <param name="capacity">The required capacity.</param>
private void EnsureCapacity(int capacity)
{
if (_elements.Length < capacity)
{
int newCapacity = Math.Max(_elements.Length * 2, capacity);
Array.Resize(ref _elements, newCapacity);
}
}
/// <summary>
/// Determines the index of a specific item in the <see cref="IList{T}"/>.
/// </summary>
/// <param name="item">The object to locate in the <see cref="IList{T}"/>.</param>
/// <returns>
/// The index of <paramref name="item"/> if found in the list; otherwise, -1.
/// </returns>
[Pure]
public int IndexOf(T item)
{
return this.IndexOf(item, 0, _count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex)
{
return this.IndexOf(item, startIndex, this.Count - startIndex, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count)
{
return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">
/// The equality comparer to use in the search.
/// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used.
/// </param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex));
Requires.Range(count >= 0 && startIndex + count <= this.Count, nameof(count));
equalityComparer = equalityComparer ?? EqualityComparer<T>.Default;
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.IndexOf(_elements, item, startIndex, count);
}
else
{
for (int i = startIndex; i < startIndex + count; i++)
{
if (equalityComparer.Equals(_elements[i], item))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item)
{
if (this.Count == 0)
{
return -1;
}
return this.LastIndexOf(item, this.Count - 1, this.Count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex)
{
if (this.Count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex));
return this.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count)
{
return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex));
Requires.Range(count >= 0 && startIndex - count + 1 >= 0, nameof(count));
equalityComparer = equalityComparer ?? EqualityComparer<T>.Default;
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.LastIndexOf(_elements, item, startIndex, count);
}
else
{
for (int i = startIndex; i >= startIndex - count + 1; i--)
{
if (equalityComparer.Equals(item, _elements[i]))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Reverses the order of elements in the collection.
/// </summary>
public void Reverse()
{
// The non-generic Array.Reverse is not used because it does not perform
// well for non-primitive value types.
// If/when a generic Array.Reverse<T> becomes available, the below code
// can be deleted and replaced with a call to Array.Reverse<T>.
int i = 0;
int j = _count - 1;
T[] array = _elements;
while (i < j)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
/// <summary>
/// Sorts the array.
/// </summary>
public void Sort()
{
if (Count > 1)
{
Array.Sort(_elements, 0, this.Count, Comparer<T>.Default);
}
}
/// <summary>
/// Sorts the elements in the entire array using
/// the specified <see cref="Comparison{T}"/>.
/// </summary>
/// <param name="comparison">
/// The <see cref="Comparison{T}"/> to use when comparing elements.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="comparison"/> is null.</exception>
[Pure]
public void Sort(Comparison<T> comparison)
{
Requires.NotNull(comparison, nameof(comparison));
if (Count > 1)
{
Array.Sort(_elements, comparison);
}
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(IComparer<T> comparer)
{
if (Count > 1)
{
Array.Sort(_elements, 0, _count, comparer);
}
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="index">The index of the first element to consider in the sort.</param>
/// <param name="count">The number of elements to include in the sort.</param>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(int index, int count, IComparer<T> comparer)
{
// Don't rely on Array.Sort's argument validation since our internal array may exceed
// the bounds of the publicly addressable region.
Requires.Range(index >= 0, nameof(index));
Requires.Range(count >= 0 && index + count <= this.Count, nameof(count));
if (count > 1)
{
Array.Sort(_elements, index, count, comparer);
}
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < this.Count; i++)
{
yield return this[i];
}
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Adds items to this collection.
/// </summary>
/// <typeparam name="TDerived">The type of source elements.</typeparam>
/// <param name="items">The source array.</param>
/// <param name="length">The number of elements to add to this array.</param>
private void AddRange<TDerived>(TDerived[] items, int length) where TDerived : T
{
this.EnsureCapacity(this.Count + length);
var offset = this.Count;
this.Count += length;
var nodes = _elements;
for (int i = 0; i < length; i++)
{
nodes[offset + i] = items[i];
}
}
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal sealed class ImmutableArrayBuilderDebuggerProxy<T>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableArray<T>.Builder _builder;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArrayBuilderDebuggerProxy{T}"/> class.
/// </summary>
/// <param name="builder">The collection to display in the debugger</param>
public ImmutableArrayBuilderDebuggerProxy(ImmutableArray<T>.Builder builder)
{
_builder = builder;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] A
{
get
{
return _builder.ToArray();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization; //for NumberFormatInfo
using TestLibrary;
/// <summary>
/// UInt16.System.IConvertible.ToString(string, IFormatProvider)
/// Converts the numeric value of this instance to its equivalent string representation
/// using the specified format and culture-specific format information.
/// </summary>
public class UInt16ToString
{
public static int Main()
{
UInt16ToString testObj = new UInt16ToString();
TestLibrary.TestFramework.BeginTestCase("for method: UInt16.System.ToString(string, IFormatProvider)");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal &= DoPosTest("PosTest1: Value is UInt16.MinValue, format is hexadecimal \"X\".", "PostTest1", UInt16.MinValue, "X", "0", CurrentNFI);
retVal &= DoPosTest("PosTest2: Value is UInt16 integer, format is hexadecimal \"X\".", "PostTest2", 8542, "X", "215E", CurrentNFI);
retVal &= DoPosTest("PosTest3: Value is UInt16.MaxValue, format is hexadecimal \"X\".", "PostTest3", UInt16.MaxValue, "X", "FFFF", CurrentNFI);
retVal &= DoPosTest("PosTest4: Value is UInt16.MinValue, format is hexadecimal \"X\".", "PosTest4", UInt16.MinValue, "X", "0", CustomNFI);
retVal &= DoPosTest("PosTest5: Value is UInt16 integer, format is general \"G\".", "PosTest5", 5641, "G", "5641", CustomNFI);
retVal &= DoPosTest("PosTest6: Value is UInt16.MaxValue, format is general \"G\".", "PosTest6", UInt16.MaxValue, "G", "65535", CustomNFI);
retVal &= DoPosTest("PosTest7: Value is UInt16 integer, format is currency \"C\".", "PosTest7", 8423, "C", "84.23,000USD", CustomNFI);
retVal &= DoPosTest("PosTest8: Value is UInt16.MaxValue, format is currency \"C\".", "PosTes8", UInt16.MaxValue, "C", "6.55.35,000USD", CustomNFI);
retVal &= DoPosTest("PosTest9: Value is UInt16.MinValue, format is currency \"C\".", "PosTes9", UInt16.MinValue, "C", "0,000USD", CustomNFI);
retVal &= DoPosTest("PosTest10: Value is UInt16 integer, format is decimal \"D\".", "PosTest10", 2351, "D", "2351", CustomNFI);
retVal &= DoPosTest("PosTest11: Value is UInt16.MaxValue integer, format is decimal \"D\".", "PosTest11", UInt16.MaxValue, "D", "65535", CustomNFI);
retVal &= DoPosTest("PosTest12: Value is UInt16.MinValue integer, format is decimal \"D\".", "PosTest12", UInt16.MinValue, "D", "0", CustomNFI);
retVal &= DoPosTest("PosTest13: Value is UInt16 integer, format is decimal \"E\".", "PosTest13", 2351, "E", TestLibrary.Utilities.IsWindows ? "2,351000E++003" : "2,351000E3", CustomNFI);
retVal &= DoPosTest("PosTest14: Value is UInt16.MaxValue integer, format is decimal \"E\".", "PosTest14", UInt16.MaxValue, "E", TestLibrary.Utilities.IsWindows ? "6,553500E++004" : "6,553500E4", CustomNFI);
retVal &= DoPosTest("PosTest15: Value is UInt16.MinValue integer, format is decimal \"E\".", "PosTest15", UInt16.MinValue, "E", TestLibrary.Utilities.IsWindows ? "0,000000E++000" : "0,000000E0", CustomNFI);
retVal &= DoPosTest("PosTest16: Value is UInt16 integer, format is decimal \"F\".", "PosTest16", 2341, "F", "2341,000", CustomNFI);
retVal &= DoPosTest("PosTest17: Value is UInt16 integer, format is decimal \"P\".", "PosTest17", 2341, "P", "234,100,0000~", CustomNFI);
retVal &= DoPosTest("PosTest18: Value is UInt16 integer, format is decimal \"N\".", "PosTest18", 2341, "N", "23#41,000", CustomNFI);
retVal &= DoPosTest("PosTest19: Value is UInt16 integer, format is decimal \"N\".", "PosTest19", 2341, null, "2341", CustomNFI);
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#endregion
#region Helper method for tests
public bool DoPosTest(string testDesc, string id, UInt16 uintA, string format, String expectedValue, NumberFormatInfo _NFI)
{
bool retVal = true;
string errorDesc;
string actualValue;
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
actualValue = uintA.ToString(format, _NFI);
if (actualValue != expectedValue)
{
errorDesc =
string.Format("The string representation of {0} is not the value {1} as expected: actual({2})",
uintA, expectedValue, actualValue);
errorDesc += "\nThe format info is \"" + ((format == null) ? "null" : format) + "\" speicifed";
TestLibrary.TestFramework.LogError(id + "_001", errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpect exception:" + e;
errorDesc += "\nThe UInt16 integer is " + uintA + ", format info is \"" + format + "\" speicifed.";
TestLibrary.TestFramework.LogError(id + "_002", errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Private Methods
private NumberFormatInfo CurrentNFI = CultureInfo.CurrentCulture.NumberFormat;
private NumberFormatInfo nfi = null;
private NumberFormatInfo CustomNFI
{
get
{
if (null == nfi)
{
nfi = new CultureInfo(CultureInfo.CurrentCulture.Name).NumberFormat;
//For "G"
// NegativeSign, NumberDecimalSeparator, NumberDecimalDigits, PositiveSign
nfi.NegativeSign = "@"; //Default: "-"
nfi.NumberDecimalSeparator = ","; //Default: "."
nfi.NumberDecimalDigits = 3; //Default: 2
nfi.PositiveSign = "++"; //Default: "+"
//For "E"
// PositiveSign, NegativeSign, and NumberDecimalSeparator.
// If precision specifier is omitted, a default of six digits after the decimal point is used.
//For "R"
// NegativeSign, NumberDecimalSeparator and PositiveSign
//For "X", The result string isn't affected by the formatting information of the current NumberFormatInfo
//For "C"
// CurrencyPositivePattern, CurrencySymbol, CurrencyDecimalDigits, CurrencyDecimalSeparator, CurrencyGroupSeparator, CurrencyGroupSizes, NegativeSign and CurrencyNegativePattern
nfi.CurrencyDecimalDigits = 3; //Default: 2
nfi.CurrencyDecimalSeparator = ","; //Default: ","
nfi.CurrencyGroupSeparator = "."; //Default: "."
nfi.CurrencyGroupSizes = new int[] { 2 }; //Default: new int[]{3}
nfi.CurrencyNegativePattern = 2; //Default: 0
nfi.CurrencyPositivePattern = 1; //Default: 0
nfi.CurrencySymbol = "USD"; //Default: "$"
//For "D"
// NegativeSign
//For "E"
// PositiveSign, NumberDecimalSeparator and NegativeSign.
// If precision specifier is omitted, a default of six digits after the decimal point is used.
nfi.PositiveSign = "++"; //Default: "+"
nfi.NumberDecimalSeparator = ","; //Default: "."
//For "F"
// NumberDecimalDigits, and NumberDecimalSeparator and NegativeSign.
nfi.NumberDecimalDigits = 3; //Default: 2
//For "N"
// NumberGroupSizes, NumberGroupSeparator, NumberDecimalSeparator, NumberDecimalDigits, NumberNegativePattern and NegativeSign.
nfi.NumberGroupSizes = new int[] { 2 }; //Default: 3
nfi.NumberGroupSeparator = "#"; //Default: ","
//For "P"
// PercentPositivePattern, PercentNegativePattern, NegativeSign, PercentSymbol, PercentDecimalDigits, PercentDecimalSeparator, PercentGroupSeparator and PercentGroupSizes
nfi.PercentPositivePattern = 1; //Default: 0
nfi.PercentNegativePattern = 2; //Default: 0
nfi.PercentSymbol = "~"; //Default: "%"
nfi.PercentDecimalDigits = 4; //Default: 2
nfi.PercentDecimalSeparator = ","; //Default: "."
nfi.PercentGroupSizes[0] = 2; //Default: 3
nfi.PercentGroupSeparator = ",";
}
return nfi;
}
}
#endregion
#region Negative tests
//FormatException
public bool NegTest1()
{
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: The format parameter is invalid -- \"R\". ";
CultureInfo culture = CultureInfo.CurrentCulture;
return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "39", "40", "R", culture);
}
public bool NegTest2()
{
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: The format parameter is invalid -- \"r\". ";
CultureInfo culture = CultureInfo.CurrentCulture;
return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "41", "42", "r", culture);
}
public bool NegTest3()
{
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTest3: The format parameter is invalid -- \"z\". ";
CultureInfo culture = CultureInfo.CurrentCulture;
return this.DoInvalidFormatTest(c_TEST_ID, c_TEST_DESC, "43", "44", "z", culture);
}
#endregion
#region Helper methods for negative tests
public bool DoInvalidFormatTest(string testId,
string testDesc,
string errorNum1,
string errorNum2,
string format,
CultureInfo culture)
{
bool retVal = true;
string errorDesc;
IFormatProvider provider;
UInt16 uintA = (UInt16)(TestLibrary.Generator.GetInt32() % (UInt16.MaxValue + 1));
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
provider = (IFormatProvider)culture.NumberFormat;
uintA.ToString(format, provider);
errorDesc = "FormatException is not thrown as expected.";
errorDesc = string.Format("\nUInt16 value is {0}, format string is {1} and the culture is {3}.",
uintA, format, culture.Name);
TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc);
retVal = false;
}
catch (FormatException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc = string.Format("\nUInt16 value is {0}, format string is {1} and the culture is {3}.",
uintA, format, culture.Name);
TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// -----------------------------------------------------------------------------------------
// <copyright file="CloudStorageAccountTests.cs" company="Microsoft">
// Copyright 2013 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>
// -----------------------------------------------------------------------------------------
using System;
using System.Globalization;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.File;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
#if WINDOWS_DESKTOP
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#endif
namespace Microsoft.WindowsAzure.Storage.Core.Util
{
[TestClass]
public class CloudStorageAccountTests : TestBase
{
private string token = "?sp=abcde&sig=1";
private string tokenWithApiVersion = "?sp=abcde&sig=1&api-version=2015-04-05";
[TestMethod]
[Description("Anonymous credentials")]
[TestCategory(ComponentCategory.Auth)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void StorageCredentialsAnonymous()
{
StorageCredentials cred = new StorageCredentials();
Assert.IsNull(cred.AccountName);
Assert.IsTrue(cred.IsAnonymous);
Assert.IsFalse(cred.IsSAS);
Assert.IsFalse(cred.IsSharedKey);
Uri testUri = new Uri("http://test/abc?querya=1");
Assert.AreEqual(testUri, cred.TransformUri(testUri));
byte[] dummyKey = { 0, 1, 2 };
string base64EncodedDummyKey = Convert.ToBase64String(dummyKey);
TestHelper.ExpectedException<InvalidOperationException>(
() => cred.UpdateKey(base64EncodedDummyKey),
"Updating shared key on an anonymous credentials instance should fail.");
}
[TestMethod]
[Description("Shared key credentials")]
[TestCategory(ComponentCategory.Auth)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void StorageCredentialsSharedKey()
{
StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey);
Assert.AreEqual(TestBase.TargetTenantConfig.AccountName, cred.AccountName, false);
Assert.IsFalse(cred.IsAnonymous);
Assert.IsFalse(cred.IsSAS);
Assert.IsTrue(cred.IsSharedKey);
Uri testUri = new Uri("http://test/abc?querya=1");
Assert.AreEqual(testUri, cred.TransformUri(testUri));
Assert.AreEqual(TestBase.TargetTenantConfig.AccountKey, cred.ExportBase64EncodedKey());
byte[] dummyKey = { 0, 1, 2 };
string base64EncodedDummyKey = Convert.ToBase64String(dummyKey);
cred.UpdateKey(base64EncodedDummyKey);
Assert.AreEqual(base64EncodedDummyKey, cred.ExportBase64EncodedKey());
#if !(WINDOWS_RT || NETCORE)
dummyKey[0] = 3;
base64EncodedDummyKey = Convert.ToBase64String(dummyKey);
cred.UpdateKey(dummyKey);
Assert.AreEqual(base64EncodedDummyKey, cred.ExportBase64EncodedKey());
#endif
}
[TestMethod]
[Description("SAS token credentials")]
[TestCategory(ComponentCategory.Auth)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void StorageCredentialsSAS()
{
StorageCredentials cred = new StorageCredentials(token);
Assert.IsNull(cred.AccountName);
Assert.IsFalse(cred.IsAnonymous);
Assert.IsTrue(cred.IsSAS);
Assert.IsFalse(cred.IsSharedKey);
Uri testUri = new Uri("http://test/abc");
Assert.AreEqual(testUri.AbsoluteUri + token + "&" + Constants.QueryConstants.ApiVersion + "=" + Constants.HeaderConstants.TargetStorageVersion, cred.TransformUri(testUri).AbsoluteUri, true);
testUri = new Uri("http://test/abc?query=a&query2=b");
string expectedUri = testUri.AbsoluteUri + "&" + token.Substring(1) + "&" + Constants.QueryConstants.ApiVersion + "=" + Constants.HeaderConstants.TargetStorageVersion;
Assert.AreEqual(expectedUri, cred.TransformUri(testUri).AbsoluteUri, true);
byte[] dummyKey = { 0, 1, 2 };
string base64EncodedDummyKey = Convert.ToBase64String(dummyKey);
TestHelper.ExpectedException<InvalidOperationException>(
() => cred.UpdateKey(base64EncodedDummyKey),
"Updating shared key on a SAS credentials instance should fail.");
TestHelper.ExpectedException<ArgumentException>(
() => new StorageCredentials(tokenWithApiVersion),
"Unexpected 'api-version' parameter included in the SAS token.");
}
[TestMethod]
[Description("CloudStorageAccount object with an empty key value.")]
[TestCategory(ComponentCategory.Auth)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void StorageCredentialsEmptyKeyValue()
{
string accountName = TestBase.TargetTenantConfig.AccountName;
string keyValue = TestBase.TargetTenantConfig.AccountKey;
string emptyKeyValueAsString = string.Empty;
string emptyKeyConnectionString = string.Format(CultureInfo.InvariantCulture, "DefaultEndpointsProtocol=https;AccountName={0};AccountKey=", accountName);
StorageCredentials credentials1 = new StorageCredentials(accountName, emptyKeyValueAsString);
Assert.AreEqual(accountName, credentials1.AccountName);
Assert.IsFalse(credentials1.IsAnonymous);
Assert.IsFalse(credentials1.IsSAS);
Assert.IsTrue(credentials1.IsSharedKey);
Assert.AreEqual(emptyKeyValueAsString, Convert.ToBase64String(credentials1.ExportKey()));
CloudStorageAccount account1 = new CloudStorageAccount(credentials1, true);
Assert.AreEqual(emptyKeyConnectionString, account1.ToString(true));
Assert.IsNotNull(account1.Credentials);
Assert.AreEqual(accountName, account1.Credentials.AccountName);
Assert.IsFalse(account1.Credentials.IsAnonymous);
Assert.IsFalse(account1.Credentials.IsSAS);
Assert.IsTrue(account1.Credentials.IsSharedKey);
Assert.AreEqual(emptyKeyValueAsString, Convert.ToBase64String(account1.Credentials.ExportKey()));
CloudStorageAccount account2 = CloudStorageAccount.Parse(emptyKeyConnectionString);
Assert.AreEqual(emptyKeyConnectionString, account2.ToString(true));
Assert.IsNotNull(account2.Credentials);
Assert.AreEqual(accountName, account2.Credentials.AccountName);
Assert.IsFalse(account2.Credentials.IsAnonymous);
Assert.IsFalse(account2.Credentials.IsSAS);
Assert.IsTrue(account2.Credentials.IsSharedKey);
Assert.AreEqual(emptyKeyValueAsString, Convert.ToBase64String(account2.Credentials.ExportKey()));
CloudStorageAccount account3;
bool isValidAccount3 = CloudStorageAccount.TryParse(emptyKeyConnectionString, out account3);
Assert.IsTrue(isValidAccount3);
Assert.IsNotNull(account3);
Assert.AreEqual(emptyKeyConnectionString, account3.ToString(true));
Assert.IsNotNull(account3.Credentials);
Assert.AreEqual(accountName, account3.Credentials.AccountName);
Assert.IsFalse(account3.Credentials.IsAnonymous);
Assert.IsFalse(account3.Credentials.IsSAS);
Assert.IsTrue(account3.Credentials.IsSharedKey);
Assert.AreEqual(emptyKeyValueAsString, Convert.ToBase64String(account3.Credentials.ExportKey()));
StorageCredentials credentials2 = new StorageCredentials(accountName, keyValue);
Assert.AreEqual(accountName, credentials2.AccountName);
Assert.IsFalse(credentials2.IsAnonymous);
Assert.IsFalse(credentials2.IsSAS);
Assert.IsTrue(credentials2.IsSharedKey);
Assert.AreEqual(keyValue, Convert.ToBase64String(credentials2.ExportKey()));
credentials2.UpdateKey(emptyKeyValueAsString, null);
Assert.AreEqual(emptyKeyValueAsString, Convert.ToBase64String(credentials2.ExportKey()));
#if !(WINDOWS_RT || NETCORE)
byte[] emptyKeyValueAsByteArray = new byte[0];
StorageCredentials credentials3 = new StorageCredentials(accountName, keyValue);
Assert.AreEqual(accountName, credentials3.AccountName);
Assert.IsFalse(credentials3.IsAnonymous);
Assert.IsFalse(credentials3.IsSAS);
Assert.IsTrue(credentials3.IsSharedKey);
Assert.AreEqual(keyValue, Convert.ToBase64String(credentials3.ExportKey()));
credentials3.UpdateKey(emptyKeyValueAsByteArray, null);
Assert.AreEqual(Convert.ToBase64String(emptyKeyValueAsByteArray), Convert.ToBase64String(credentials3.ExportKey()));
#endif
}
[TestMethod]
[Description("CloudStorageAccount object with a null key value.")]
[TestCategory(ComponentCategory.Auth)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void StorageCredentialsNullKeyValue()
{
string accountName = TestBase.TargetTenantConfig.AccountName;
string keyValue = TestBase.TargetTenantConfig.AccountKey;
string nullKeyValueAsString = null;
TestHelper.ExpectedException<ArgumentNullException>(() =>
{
StorageCredentials credentials1 = new StorageCredentials(accountName, nullKeyValueAsString);
}, "Cannot create key with a null value.");
StorageCredentials credentials2 = new StorageCredentials(accountName, keyValue);
Assert.AreEqual(accountName, credentials2.AccountName);
Assert.IsFalse(credentials2.IsAnonymous);
Assert.IsFalse(credentials2.IsSAS);
Assert.IsTrue(credentials2.IsSharedKey);
Assert.AreEqual(keyValue, Convert.ToBase64String(credentials2.ExportKey()));
TestHelper.ExpectedException<ArgumentNullException>(() =>
{
credentials2.UpdateKey(nullKeyValueAsString, null);
}, "Cannot update key with a null string value.");
#if !(WINDOWS_RT || NETCORE)
byte[] nullKeyValueAsByteArray = null;
StorageCredentials credentials3 = new StorageCredentials(accountName, keyValue);
Assert.AreEqual(accountName, credentials3.AccountName);
Assert.IsFalse(credentials3.IsAnonymous);
Assert.IsFalse(credentials3.IsSAS);
Assert.IsTrue(credentials3.IsSharedKey);
Assert.AreEqual(keyValue, Convert.ToBase64String(credentials3.ExportKey()));
TestHelper.ExpectedException<ArgumentNullException>(() =>
{
credentials3.UpdateKey(nullKeyValueAsByteArray, null);
}, "Cannot update key with a null byte array value.");
#endif
}
[TestMethod]
[Description("Compare credentials for equality")]
[TestCategory(ComponentCategory.Auth)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void StorageCredentialsEquality()
{
StorageCredentials credSharedKey1 = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey);
StorageCredentials credSharedKey2 = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey);
StorageCredentials credSharedKey3 = new StorageCredentials(TestBase.TargetTenantConfig.AccountName + "1", TestBase.TargetTenantConfig.AccountKey);
StorageCredentials credSharedKey4 = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, Convert.ToBase64String(new byte[] { 0, 1, 2 }));
StorageCredentials credSAS1 = new StorageCredentials(token);
StorageCredentials credSAS2 = new StorageCredentials(token);
StorageCredentials credSAS3 = new StorageCredentials(token + "1");
StorageCredentials credAnonymous1 = new StorageCredentials();
StorageCredentials credAnonymous2 = new StorageCredentials();
StorageCredentials tokenCredential1 = new StorageCredentials(new TokenCredential("0"));
StorageCredentials tokenCredential2 = new StorageCredentials(new TokenCredential("1"));
StorageCredentials tokenCredential3 = new StorageCredentials(new TokenCredential("0"));
Assert.IsTrue(credSharedKey1.Equals(credSharedKey2));
Assert.IsFalse(credSharedKey1.Equals(credSharedKey3));
Assert.IsFalse(credSharedKey1.Equals(credSharedKey4));
Assert.IsTrue(credSAS1.Equals(credSAS2));
Assert.IsFalse(credSAS1.Equals(credSAS3));
Assert.IsTrue(credAnonymous1.Equals(credAnonymous2));
Assert.IsFalse(credSharedKey1.Equals(credSAS1));
Assert.IsFalse(credSharedKey1.Equals(credAnonymous1));
Assert.IsFalse(credSAS1.Equals(credAnonymous1));
Assert.IsFalse(tokenCredential1.Equals(tokenCredential2));
Assert.IsTrue(tokenCredential1.Equals(tokenCredential3));
}
private void AccountsAreEqual(CloudStorageAccount a, CloudStorageAccount b)
{
// endpoints are the same
Assert.AreEqual(a.BlobEndpoint, b.BlobEndpoint);
Assert.AreEqual(a.QueueEndpoint, b.QueueEndpoint);
Assert.AreEqual(a.TableEndpoint, b.TableEndpoint);
Assert.AreEqual(a.FileEndpoint, b.FileEndpoint);
// storage uris are the same
Assert.AreEqual(a.BlobStorageUri, b.BlobStorageUri);
Assert.AreEqual(a.QueueStorageUri, b.QueueStorageUri);
Assert.AreEqual(a.TableStorageUri, b.TableStorageUri);
Assert.AreEqual(a.FileStorageUri, b.FileStorageUri);
// seralized representatons are the same.
string aToStringNoSecrets = a.ToString();
string aToStringWithSecrets = a.ToString(true);
string bToStringNoSecrets = b.ToString(false);
string bToStringWithSecrets = b.ToString(true);
Assert.AreEqual(aToStringNoSecrets, bToStringNoSecrets, false);
Assert.AreEqual(aToStringWithSecrets, bToStringWithSecrets, false);
// credentials are the same
if (a.Credentials != null && b.Credentials != null)
{
Assert.AreEqual(a.Credentials.IsAnonymous, b.Credentials.IsAnonymous);
Assert.AreEqual(a.Credentials.IsSAS, b.Credentials.IsSAS);
Assert.AreEqual(a.Credentials.IsSharedKey, b.Credentials.IsSharedKey);
// make sure
if (!a.Credentials.IsAnonymous &&
a.Credentials != CloudStorageAccount.DevelopmentStorageAccount.Credentials &&
b.Credentials != CloudStorageAccount.DevelopmentStorageAccount.Credentials)
{
Assert.AreNotEqual(aToStringWithSecrets, bToStringNoSecrets, true);
}
}
else if (a.Credentials == null && b.Credentials == null)
{
return;
}
else
{
Assert.Fail("credentials mismatch");
}
}
[TestMethod]
[Description("DevStore account")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountDevelopmentStorageAccount()
{
CloudStorageAccount devstoreAccount = CloudStorageAccount.DevelopmentStorageAccount;
Assert.AreEqual(devstoreAccount.BlobEndpoint, new Uri("http://127.0.0.1:10000/devstoreaccount1"));
Assert.AreEqual(devstoreAccount.QueueEndpoint, new Uri("http://127.0.0.1:10001/devstoreaccount1"));
Assert.AreEqual(devstoreAccount.TableEndpoint, new Uri("http://127.0.0.1:10002/devstoreaccount1"));
Assert.AreEqual(devstoreAccount.BlobStorageUri.SecondaryUri, new Uri("http://127.0.0.1:10000/devstoreaccount1-secondary"));
Assert.AreEqual(devstoreAccount.QueueStorageUri.SecondaryUri, new Uri("http://127.0.0.1:10001/devstoreaccount1-secondary"));
Assert.AreEqual(devstoreAccount.TableStorageUri.SecondaryUri, new Uri("http://127.0.0.1:10002/devstoreaccount1-secondary"));
Assert.IsNull(devstoreAccount.FileStorageUri);
string devstoreAccountToStringWithSecrets = devstoreAccount.ToString(true);
CloudStorageAccount testAccount = CloudStorageAccount.Parse(devstoreAccountToStringWithSecrets);
AccountsAreEqual(testAccount, devstoreAccount);
CloudStorageAccount acct;
if (!CloudStorageAccount.TryParse(devstoreAccountToStringWithSecrets, out acct))
{
Assert.Fail("Expected TryParse success.");
}
}
[TestMethod]
[Description("Regular account with HTTP")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountDefaultStorageAccountWithHttp()
{
StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey);
CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(cred, false);
Assert.AreEqual(cloudStorageAccount.BlobEndpoint,
new Uri(String.Format("http://{0}.blob.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.QueueEndpoint,
new Uri(String.Format("http://{0}.queue.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.TableEndpoint,
new Uri(String.Format("http://{0}.table.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.FileEndpoint,
new Uri(String.Format("http://{0}.file.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.BlobStorageUri.SecondaryUri,
new Uri(String.Format("http://{0}-secondary.blob.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.QueueStorageUri.SecondaryUri,
new Uri(String.Format("http://{0}-secondary.queue.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.TableStorageUri.SecondaryUri,
new Uri(String.Format("http://{0}-secondary.table.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.FileStorageUri.SecondaryUri,
new Uri(String.Format("http://{0}-secondary.file.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
string cloudStorageAccountToStringNoSecrets = cloudStorageAccount.ToString();
string cloudStorageAccountToStringWithSecrets = cloudStorageAccount.ToString(true);
CloudStorageAccount testAccount = CloudStorageAccount.Parse(cloudStorageAccountToStringWithSecrets);
AccountsAreEqual(testAccount, cloudStorageAccount);
}
[TestMethod]
[Description("Regular account with HTTPS")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountDefaultStorageAccountWithHttps()
{
StorageCredentials cred = new StorageCredentials(TestBase.TargetTenantConfig.AccountName, TestBase.TargetTenantConfig.AccountKey);
CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(cred, true);
Assert.AreEqual(cloudStorageAccount.BlobEndpoint,
new Uri(String.Format("https://{0}.blob.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.QueueEndpoint,
new Uri(String.Format("https://{0}.queue.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.TableEndpoint,
new Uri(String.Format("https://{0}.table.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.FileEndpoint,
new Uri(String.Format("https://{0}.file.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.BlobStorageUri.SecondaryUri,
new Uri(String.Format("https://{0}-secondary.blob.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.QueueStorageUri.SecondaryUri,
new Uri(String.Format("https://{0}-secondary.queue.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.TableStorageUri.SecondaryUri,
new Uri(String.Format("https://{0}-secondary.table.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
Assert.AreEqual(cloudStorageAccount.FileStorageUri.SecondaryUri,
new Uri(String.Format("https://{0}-secondary.file.core.windows.net", TestBase.TargetTenantConfig.AccountName)));
string cloudStorageAccountToStringWithSecrets = cloudStorageAccount.ToString(true);
CloudStorageAccount testAccount = CloudStorageAccount.Parse(cloudStorageAccountToStringWithSecrets);
AccountsAreEqual(testAccount, cloudStorageAccount);
}
[TestMethod]
[Description("Regular account with HTTP")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountEndpointSuffixWithHttp()
{
const string TestEndpointSuffix = "fake.endpoint.suffix";
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(
string.Format(
"DefaultEndpointsProtocol=http;AccountName={0};AccountKey={1};EndpointSuffix={2};",
TestBase.TargetTenantConfig.AccountName,
TestBase.TargetTenantConfig.AccountKey,
TestEndpointSuffix));
Assert.AreEqual(cloudStorageAccount.BlobEndpoint,
new Uri(String.Format("http://{0}.blob.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.QueueEndpoint,
new Uri(String.Format("http://{0}.queue.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.TableEndpoint,
new Uri(String.Format("http://{0}.table.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.FileEndpoint,
new Uri(String.Format("http://{0}.file.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.BlobStorageUri.SecondaryUri,
new Uri(String.Format("http://{0}-secondary.blob.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.QueueStorageUri.SecondaryUri,
new Uri(String.Format("http://{0}-secondary.queue.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.TableStorageUri.SecondaryUri,
new Uri(String.Format("http://{0}-secondary.table.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.FileStorageUri.SecondaryUri,
new Uri(String.Format("http://{0}-secondary.file.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
string cloudStorageAccountToStringWithSecrets = cloudStorageAccount.ToString(true);
CloudStorageAccount testAccount = CloudStorageAccount.Parse(cloudStorageAccountToStringWithSecrets);
AccountsAreEqual(testAccount, cloudStorageAccount);
}
[TestMethod]
[Description("Regular account with HTTPS")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountEndpointSuffixWithHttps()
{
const string TestEndpointSuffix = "fake.endpoint.suffix";
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};EndpointSuffix={2};",
TestBase.TargetTenantConfig.AccountName,
TestBase.TargetTenantConfig.AccountKey,
TestEndpointSuffix));
Assert.AreEqual(cloudStorageAccount.BlobEndpoint,
new Uri(String.Format("https://{0}.blob.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.QueueEndpoint,
new Uri(String.Format("https://{0}.queue.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.TableEndpoint,
new Uri(String.Format("https://{0}.table.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.FileEndpoint,
new Uri(String.Format("https://{0}.file.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.BlobStorageUri.SecondaryUri,
new Uri(String.Format("https://{0}-secondary.blob.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.QueueStorageUri.SecondaryUri,
new Uri(String.Format("https://{0}-secondary.queue.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.TableStorageUri.SecondaryUri,
new Uri(String.Format("https://{0}-secondary.table.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
Assert.AreEqual(cloudStorageAccount.FileStorageUri.SecondaryUri,
new Uri(String.Format("https://{0}-secondary.file.{1}", TestBase.TargetTenantConfig.AccountName, TestEndpointSuffix)));
string cloudStorageAccountToStringWithSecrets = cloudStorageAccount.ToString(true);
CloudStorageAccount testAccount = CloudStorageAccount.Parse(cloudStorageAccountToStringWithSecrets);
AccountsAreEqual(testAccount, cloudStorageAccount);
}
[TestMethod]
[Description("Regular account with HTTP")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountEndpointSuffixWithBlob()
{
const string TestEndpointSuffix = "fake.endpoint.suffix";
const string AlternateBlobEndpoint = "http://blob.other.endpoint/";
CloudStorageAccount testAccount =
CloudStorageAccount.Parse(
string.Format(
"DefaultEndpointsProtocol=http;AccountName={0};AccountKey={1};EndpointSuffix={2};BlobEndpoint={3}",
TestBase.TargetTenantConfig.AccountName,
TestBase.TargetTenantConfig.AccountKey,
TestEndpointSuffix,
AlternateBlobEndpoint));
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(testAccount.ToString(true));
// make sure it round trips
this.AccountsAreEqual(testAccount, cloudStorageAccount);
}
[TestMethod]
[Description("Regular account with HTTP")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountConnectionStringRoundtrip()
{
string[] accountKeyParams = new[]
{
TestBase.TargetTenantConfig.AccountName,
TestBase.TargetTenantConfig.AccountKey,
"fake.endpoint.suffix",
"https://primary.endpoint/",
"https://secondary.endpoint/"
};
string[] accountSasParams = new[]
{
TestBase.TargetTenantConfig.AccountName,
"sasTest",
"fake.endpoint.suffix",
"https://primary.endpoint/",
"https://secondary.endpoint/"
};
// account key
string accountString1 =
string.Format(
"DefaultEndpointsProtocol=http;AccountName={0};AccountKey={1};EndpointSuffix={2};",
accountKeyParams);
string accountString2 =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};",
accountKeyParams);
string accountString3 =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};QueueEndpoint={3}",
accountKeyParams);
string accountString4 =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};EndpointSuffix={2};QueueEndpoint={3}",
accountKeyParams);
connectionStringRoundtripHelper(accountString1);
connectionStringRoundtripHelper(accountString2);
connectionStringRoundtripHelper(accountString3);
connectionStringRoundtripHelper(accountString4);
string accountString5 =
string.Format(
"AccountName={0};AccountKey={1};EndpointSuffix={2};",
accountKeyParams);
string accountString6 =
string.Format(
"AccountName={0};AccountKey={1};",
accountKeyParams);
string accountString7 =
string.Format(
"AccountName={0};AccountKey={1};QueueEndpoint={3}",
accountKeyParams);
string accountString8 =
string.Format(
"AccountName={0};AccountKey={1};EndpointSuffix={2};QueueEndpoint={3}",
accountKeyParams);
connectionStringRoundtripHelper(accountString5);
connectionStringRoundtripHelper(accountString6);
connectionStringRoundtripHelper(accountString7);
connectionStringRoundtripHelper(accountString8);
// shared access
string accountString9 =
string.Format(
"DefaultEndpointsProtocol=http;AccountName={0};SharedAccessSignature={1};EndpointSuffix={2};",
accountSasParams);
string accountString10 =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};SharedAccessSignature={1};",
accountSasParams);
string accountString11 =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};SharedAccessSignature={1};QueueEndpoint={3}",
accountSasParams);
string accountString12 =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};SharedAccessSignature={1};EndpointSuffix={2};QueueEndpoint={3}",
accountSasParams);
connectionStringRoundtripHelper(accountString9);
connectionStringRoundtripHelper(accountString10);
connectionStringRoundtripHelper(accountString11);
connectionStringRoundtripHelper(accountString12);
string accountString13 =
string.Format(
"AccountName={0};SharedAccessSignature={1};EndpointSuffix={2};",
accountSasParams);
string accountString14 =
string.Format(
"AccountName={0};SharedAccessSignature={1};",
accountSasParams);
string accountString15 =
string.Format(
"AccountName={0};SharedAccessSignature={1};QueueEndpoint={3}",
accountSasParams);
string accountString16 =
string.Format(
"AccountName={0};SharedAccessSignature={1};EndpointSuffix={2};QueueEndpoint={3}",
accountSasParams);
connectionStringRoundtripHelper(accountString13);
connectionStringRoundtripHelper(accountString14);
connectionStringRoundtripHelper(accountString15);
connectionStringRoundtripHelper(accountString16);
// shared access no account name
string accountString17 =
string.Format(
"SharedAccessSignature={1};QueueEndpoint={3}",
accountSasParams);
connectionStringRoundtripHelper(accountString17);
}
[TestMethod]
[Description("Regular account with HTTP")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountConnectionStringExpectedExceptions()
{
string[][] endpointCombinations = new[]
{
new[] { "BlobEndpoint={3}", "BlobSecondaryEndpoint={4}", "BlobEndpoint={3};BlobSecondaryEndpoint={4}" },
new[] { "QueueEndpoint={3}", "QueueSecondaryEndpoint={4}", "QueueEndpoint={3};QueueSecondaryEndpoint={4}" },
new[] { "TableEndpoint={3}", "TableSecondaryEndpoint={4}", "TableEndpoint={3};TableSecondaryEndpoint={4}" },
new[] { "FileEndpoint={3}", "FileSecondaryEndpoint={4}", "FileEndpoint={3};FileSecondaryEndpoint={4}" }
};
string[] accountKeyParams = new[]
{
TestBase.TargetTenantConfig.AccountName,
TestBase.TargetTenantConfig.AccountKey,
"fake.endpoint.suffix",
"https://primary.endpoint/",
"https://secondary.endpoint/"
};
string[] accountSasParams = new[]
{
TestBase.TargetTenantConfig.AccountName,
"sasTest",
"fake.endpoint.suffix",
"https://primary.endpoint/",
"https://secondary.endpoint/"
};
foreach (string[] endpointCombination in endpointCombinations)
{
// account key
string accountStringKeyPrimary =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};EndpointSuffix={2};" + endpointCombination[0],
accountKeyParams
);
string accountStringKeySecondary =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};EndpointSuffix={2};" + endpointCombination[1],
accountKeyParams
);
string accountStringKeyPrimarySecondary =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1};EndpointSuffix={2};" + endpointCombination[2],
accountKeyParams
);
CloudStorageAccount.Parse(accountStringKeyPrimary); // no exception expected
TestHelper.ExpectedException<FormatException>(() => CloudStorageAccount.Parse(accountStringKeySecondary), "connection string parse", "No valid combination of account information found.");
CloudStorageAccount.Parse(accountStringKeyPrimarySecondary); // no exception expected
// account key, no default protocol
string accountStringKeyNoDefaultProtocolPrimary =
string.Format(
"AccountName={0};AccountKey={1};EndpointSuffix={2};" + endpointCombination[0],
accountKeyParams
);
string accountStringKeyNoDefaultProtocolSecondary =
string.Format(
"AccountName={0};AccountKey={1};EndpointSuffix={2};" + endpointCombination[1],
accountKeyParams
);
string accountStringKeyNoDefaultProtocolPrimarySecondary =
string.Format(
"AccountName={0};AccountKey={1};EndpointSuffix={2};" + endpointCombination[2],
accountKeyParams
);
CloudStorageAccount.Parse(accountStringKeyNoDefaultProtocolPrimary); // no exception expected
TestHelper.ExpectedException<FormatException>(() => CloudStorageAccount.Parse(accountStringKeyNoDefaultProtocolSecondary), "connection string parse", "No valid combination of account information found.");
CloudStorageAccount.Parse(accountStringKeyNoDefaultProtocolPrimarySecondary); // no exception expected
// SAS
string accountStringSasPrimary =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};SharedAccessSignature={1};EndpointSuffix={2};" + endpointCombination[0],
accountSasParams
);
string accountStringSasSecondary =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};SharedAccessSignature={1};EndpointSuffix={2};" + endpointCombination[1],
accountSasParams
);
string accountStringSasPrimarySecondary =
string.Format(
"DefaultEndpointsProtocol=https;AccountName={0};SharedAccessSignature={1};EndpointSuffix={2};" + endpointCombination[2],
accountSasParams
);
CloudStorageAccount.Parse(accountStringSasPrimary); // no exception expected
TestHelper.ExpectedException<FormatException>(() => CloudStorageAccount.Parse(accountStringSasSecondary), "connection string parse", "No valid combination of account information found.");
CloudStorageAccount.Parse(accountStringSasPrimarySecondary); // no exception expected
// SAS, no default protocol
string accountStringSasNoDefaultProtocolPrimary =
string.Format(
"AccountName={0};SharedAccessSignature={1};EndpointSuffix={2};" + endpointCombination[0],
accountSasParams
);
string accountStringSasNoDefaultProtocolSecondary =
string.Format(
"AccountName={0};SharedAccessSignature={1};EndpointSuffix={2};" + endpointCombination[1],
accountSasParams
);
string accountStringSasNoDefaultProtocolPrimarySecondary =
string.Format(
"AccountName={0};SharedAccessSignature={1};EndpointSuffix={2};" + endpointCombination[2],
accountSasParams
);
CloudStorageAccount.Parse(accountStringSasNoDefaultProtocolPrimary); // no exception expected
TestHelper.ExpectedException<FormatException>(() => CloudStorageAccount.Parse(accountStringSasNoDefaultProtocolSecondary), "connection string parse", "No valid combination of account information found.");
CloudStorageAccount.Parse(accountStringSasNoDefaultProtocolPrimarySecondary); // no exception expected
// SAS without AccountName
string accountStringSasNoNameNoEndpoint =
string.Format(
"SharedAccessSignature={1}",
accountSasParams
);
string accountStringSasNoNamePrimary =
string.Format(
"SharedAccessSignature={1};" + endpointCombination[0],
accountSasParams
);
string accountStringSasNoNameSecondary =
string.Format(
"SharedAccessSignature={1};" + endpointCombination[1],
accountSasParams
);
string accountStringSasNoNamePrimarySecondary =
string.Format(
"SharedAccessSignature={1};" + endpointCombination[2],
accountSasParams
);
TestHelper.ExpectedException<FormatException>(() => CloudStorageAccount.Parse(accountStringSasNoNameNoEndpoint), "connection string parse", "No valid combination of account information found.");
CloudStorageAccount.Parse(accountStringSasNoNamePrimary); // no exception expected
TestHelper.ExpectedException<FormatException>(() => CloudStorageAccount.Parse(accountStringSasNoNameSecondary), "connection string parse", "No valid combination of account information found.");
CloudStorageAccount.Parse(accountStringSasNoNamePrimarySecondary); // no exception expected
}
}
private void connectionStringRoundtripHelper(string accountString)
{
CloudStorageAccount originalAccount = CloudStorageAccount.Parse(accountString);
string copiedAccountString = originalAccount.ToString(true);
CloudStorageAccount copiedAccount = CloudStorageAccount.Parse(copiedAccountString);
// make sure it round trips
this.AccountsAreEqual(originalAccount, copiedAccount);
}
[TestMethod]
[Description("Service client creation methods")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountClientMethods()
{
CloudStorageAccount account = new CloudStorageAccount(TestBase.StorageCredentials, false);
CloudBlobClient blob = account.CreateCloudBlobClient();
CloudQueueClient queue = account.CreateCloudQueueClient();
CloudTableClient table = account.CreateCloudTableClient();
CloudFileClient file = account.CreateCloudFileClient();
// check endpoints
Assert.AreEqual(account.BlobEndpoint, blob.BaseUri, "Blob endpoint doesn't match account");
Assert.AreEqual(account.QueueEndpoint, queue.BaseUri, "Queue endpoint doesn't match account");
Assert.AreEqual(account.TableEndpoint, table.BaseUri, "Table endpoint doesn't match account");
Assert.AreEqual(account.FileEndpoint, file.BaseUri, "File endpoint doesn't match account");
// check storage uris
Assert.AreEqual(account.BlobStorageUri, blob.StorageUri, "Blob endpoint doesn't match account");
Assert.AreEqual(account.QueueStorageUri, queue.StorageUri, "Queue endpoint doesn't match account");
Assert.AreEqual(account.TableStorageUri, table.StorageUri, "Table endpoint doesn't match account");
Assert.AreEqual(account.FileStorageUri, file.StorageUri, "File endpoint doesn't match account");
// check creds
Assert.AreEqual(account.Credentials, blob.Credentials, "Blob creds don't match account");
Assert.AreEqual(account.Credentials, queue.Credentials, "Queue creds don't match account");
Assert.AreEqual(account.Credentials, table.Credentials, "Table creds don't match account");
Assert.AreEqual(account.Credentials, file.Credentials, "File creds don't match account");
}
[TestMethod]
[Description("Service client creation methods")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountClientUriVerify()
{
string myAccountName = TestBase.TargetTenantConfig.AccountName;
string myAccountKey = TestBase.TargetTenantConfig.AccountKey;
#region sample_CloudStorageAccount_Constructor
// Create a CloudStorageAccount object using account name and key.
// The account name should be just the name of a Storage Account, not a URI, and
// not including the suffix. The key should be a base-64 encoded string that you
// can acquire from the portal, or from the management plane.
// This will have full permissions to all operations on the account.
StorageCredentials storageCredentials = new StorageCredentials(myAccountName, myAccountKey);
CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(storageCredentials, useHttps: true);
// Create a CloudBlobClient object from the storage account.
// This object is the root object for all operations on the
// blob service for this particular account.
CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
// Get a reference to a CloudBlobContainer object in this account.
// This object can be used to create the container on the service,
// list blobs, delete the container, etc. This operation does not make a
// call to the Azure Storage service. It neither creates the container
// on the service, nor validates its existence.
CloudBlobContainer container = blobClient.GetContainerReference("container1");
// Create a CloudQueueClient object from the storage account.
// This object is the root object for all operations on the
// queue service for this particular account.
CloudQueueClient queueClient = cloudStorageAccount.CreateCloudQueueClient();
// Get a reference to a CloudQueue object in this account.
// This object can be used to create the queue on the service,
// delete the queue, add messages, etc. This operation does not
// make a call to the Azure Storage service. It neither creates
// the queue on the service, nor validates its existence.
CloudQueue queue = queueClient.GetQueueReference("queue1");
// Create a CloudTableClient object from the storage account.
// This object is the root object for all operations on the
// table service for this particular account.
CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient();
// Get a reference to a CloudTable object in this account.
// This object can be used to create the table on the service,
// delete the table, insert entities, etc. This operation does
// not make a call to the Azure Storage service. It neither
// creates the table on the service, nor validates its existence.
CloudTable table = tableClient.GetTableReference("table1");
// Create a CloudFileClient object from the storage account.
// This object is the root object for all operations on the
// file service for this particular account.
CloudFileClient fileClient = cloudStorageAccount.CreateCloudFileClient();
// Get a reference to a CloudFileShare object in this account.
// This object can be used to create the share on the service,
// delete the share, list files and directories, etc. This operation
// does not make a call to the Azure Storage service. It neither
// creates the share on the service, nor validates its existence.
CloudFileShare share = fileClient.GetShareReference("share1");
#endregion
Assert.AreEqual(cloudStorageAccount.BlobEndpoint.ToString() + "container1", container.Uri.ToString());
Assert.AreEqual(cloudStorageAccount.QueueEndpoint.ToString() + "queue1", queue.Uri.ToString());
Assert.AreEqual(cloudStorageAccount.TableEndpoint.ToString() + "table1", table.Uri.ToString());
Assert.AreEqual(cloudStorageAccount.FileEndpoint.ToString() + "share1", share.Uri.ToString());
}
[TestMethod]
[Description("TryParse should return false for invalid connection strings")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountTryParseNullEmpty()
{
CloudStorageAccount account;
// TryParse should not throw exception when passing in null or empty string
Assert.IsFalse(CloudStorageAccount.TryParse(null, out account));
Assert.IsFalse(CloudStorageAccount.TryParse(string.Empty, out account));
}
[TestMethod]
[Description("UseDevelopmentStorage=false should fail")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountDevStoreNonTrueFails()
{
CloudStorageAccount account;
Assert.IsFalse(CloudStorageAccount.TryParse("UseDevelopmentStorage=false", out account));
}
[TestMethod]
[Description("UseDevelopmentStorage should fail when used with an account name")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountDevStorePlusAccountFails()
{
CloudStorageAccount account;
Assert.IsFalse(CloudStorageAccount.TryParse("UseDevelopmentStorage=false;AccountName=devstoreaccount1", out account));
}
[TestMethod]
[Description("UseDevelopmentStorage should fail when used with a custom endpoint")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountDevStorePlusEndpointFails()
{
CloudStorageAccount account;
Assert.IsFalse(CloudStorageAccount.TryParse("UseDevelopmentStorage=false;BlobEndpoint=http://127.0.0.1:1000/devstoreaccount1", out account));
}
[TestMethod]
[Description("Custom endpoints")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountDefaultEndpointOverride()
{
CloudStorageAccount account;
Assert.IsTrue(CloudStorageAccount.TryParse("DefaultEndpointsProtocol=http;BlobEndpoint=http://customdomain.com/;AccountName=asdf;AccountKey=123=", out account));
Assert.AreEqual(new Uri("http://customdomain.com/"), account.BlobEndpoint);
Assert.IsNull(account.BlobStorageUri.SecondaryUri);
}
[TestMethod]
[Description("Use DevStore with a proxy")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountDevStoreProxyUri()
{
CloudStorageAccount account;
Assert.IsTrue(CloudStorageAccount.TryParse("UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://ipv4.fiddler", out account));
Assert.AreEqual(new Uri("http://ipv4.fiddler:10000/devstoreaccount1"), account.BlobEndpoint);
Assert.AreEqual(new Uri("http://ipv4.fiddler:10001/devstoreaccount1"), account.QueueEndpoint);
Assert.AreEqual(new Uri("http://ipv4.fiddler:10002/devstoreaccount1"), account.TableEndpoint);
Assert.AreEqual(new Uri("http://ipv4.fiddler:10000/devstoreaccount1-secondary"), account.BlobStorageUri.SecondaryUri);
Assert.AreEqual(new Uri("http://ipv4.fiddler:10001/devstoreaccount1-secondary"), account.QueueStorageUri.SecondaryUri);
Assert.AreEqual(new Uri("http://ipv4.fiddler:10002/devstoreaccount1-secondary"), account.TableStorageUri.SecondaryUri);
Assert.IsNull(account.FileStorageUri);
}
[TestMethod]
[Description("ToString method for DevStore account should not return endpoint info")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountDevStoreRoundtrip()
{
string accountString = "UseDevelopmentStorage=true";
Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true));
}
[TestMethod]
[Description("ToString method for DevStore account with a proxy should not return endpoint info")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountDevStoreProxyRoundtrip()
{
string accountString = "UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://ipv4.fiddler/";
Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true));
}
[TestMethod]
[Description("ToString method for regular account should return the same connection string")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountDefaultCloudRoundtrip()
{
string accountString = "DefaultEndpointsProtocol=http;AccountName=test;AccountKey=abc=";
Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true));
}
[TestMethod]
[Description("ToString method for anonymous credentials should return the same connection string")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountAnonymousRoundtrip()
{
string accountString = "BlobEndpoint=http://blobs/";
Assert.AreEqual(accountString, CloudStorageAccount.Parse(accountString).ToString(true));
CloudStorageAccount account = new CloudStorageAccount(null, new Uri("http://blobs/"), null, null, null);
AccountsAreEqual(account, CloudStorageAccount.Parse(account.ToString(true)));
}
[TestMethod]
[Description("Exporting account key should be possible both as a byte array and a Base64 encoded string")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void CloudStorageAccountExportKey()
{
string accountKeyString = "abc2564=";
string accountString = "BlobEndpoint=http://blobs/;AccountName=test;AccountKey=" + accountKeyString;
CloudStorageAccount account = CloudStorageAccount.Parse(accountString);
StorageCredentials accountAndKey = (StorageCredentials)account.Credentials;
string key = accountAndKey.ExportBase64EncodedKey();
Assert.AreEqual(accountKeyString, key);
byte[] keyBytes = accountAndKey.ExportKey();
byte[] expectedKeyBytes = Convert.FromBase64String(accountKeyString);
for (int i = 0; i < expectedKeyBytes.Length; i++)
{
Assert.AreEqual(expectedKeyBytes[i], keyBytes[i]);
}
Assert.AreEqual(expectedKeyBytes.Length, keyBytes.Length);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Globalization;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Numerics.Tests
{
public class Vector3Tests
{
[Fact]
public void Vector3MarshalSizeTest()
{
Assert.Equal(12, Marshal.SizeOf(typeof(Vector3)));
Assert.Equal(12, Marshal.SizeOf(new Vector3()));
}
[Fact]
public void Vector3CopyToTest()
{
Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f);
Single[] a = new Single[4];
Single[] b = new Single[3];
v1.CopyTo(a, 1);
v1.CopyTo(b);
Assert.Equal(0.0f, a[0]);
Assert.Equal(2.0f, a[1]);
Assert.Equal(3.0f, a[2]);
Assert.Equal(3.3f, a[3]);
Assert.Equal(2.0f, b[0]);
Assert.Equal(3.0f, b[1]);
Assert.Equal(3.3f, b[2]);
}
[Fact]
public void Vector3GetHashCodeTest()
{
Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f);
Vector3 v2 = new Vector3(4.5f, 6.5f, 7.5f);
Vector3 v3 = new Vector3(2.0f, 3.0f, 3.3f);
Vector3 v5 = new Vector3(3.0f, 2.0f, 3.3f);
Assert.True(v1.GetHashCode() == v1.GetHashCode());
Assert.False(v1.GetHashCode() == v5.GetHashCode());
Assert.True(v1.GetHashCode() == v3.GetHashCode());
Vector3 v4 = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 v6 = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 v7 = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 v8 = new Vector3(1.0f, 1.0f, 1.0f);
Vector3 v9 = new Vector3(1.0f, 1.0f, 0.0f);
Assert.False(v4.GetHashCode() == v6.GetHashCode());
Assert.False(v4.GetHashCode() == v7.GetHashCode());
Assert.False(v4.GetHashCode() == v8.GetHashCode());
Assert.False(v7.GetHashCode() == v6.GetHashCode());
Assert.False(v8.GetHashCode() == v6.GetHashCode());
Assert.True(v8.GetHashCode() == v7.GetHashCode());
Assert.False(v8.GetHashCode() == v9.GetHashCode());
Assert.False(v7.GetHashCode() == v9.GetHashCode());
}
[Fact]
public void Vector3ToStringTest()
{
Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f);
string v1str = v1.ToString();
Assert.Equal("<2, 3, 3.3>", v1str);
string v1strformatted = v1.ToString("c", new CultureInfo("en-US"));
Assert.Equal("<$2.00, $3.00, $3.30>", v1strformatted);
string v2strformatted = v1.ToString("c");
Assert.Equal(string.Format("<{0:C}, {1:C}, {2:C}>", 2, 3, 3.3), v2strformatted);
}
// A test for Cross (Vector3f, Vector3f)
[Fact]
public void Vector3CrossTest()
{
Vector3 a = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 b = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 expected = new Vector3(0.0f, 0.0f, 1.0f);
Vector3 actual;
actual = Vector3.Cross(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Cross did not return the expected value.");
}
// A test for Cross (Vector3f, Vector3f)
// Cross test of the same vector
[Fact]
public void Vector3CrossTest1()
{
Vector3 a = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 b = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 expected = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 actual = Vector3.Cross(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Cross did not return the expected value.");
}
// A test for Distance (Vector3f, Vector3f)
[Fact]
public void Vector3DistanceTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float expected = (float)System.Math.Sqrt(27);
float actual;
actual = Vector3.Distance(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Distance did not return the expected value.");
}
// A test for Distance (Vector3f, Vector3f)
// Distance from the same point
[Fact]
public void Vector3DistanceTest1()
{
Vector3 a = new Vector3(1.051f, 2.05f, 3.478f);
Vector3 b = new Vector3(new Vector2(1.051f, 0.0f), 1);
b.Y = 2.05f;
b.Z = 3.478f;
float actual = Vector3.Distance(a, b);
Assert.Equal(0.0f, actual);
}
// A test for DistanceSquared (Vector3f, Vector3f)
[Fact]
public void Vector3DistanceSquaredTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float expected = 27.0f;
float actual;
actual = Vector3.DistanceSquared(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.DistanceSquared did not return the expected value.");
}
// A test for Dot (Vector3f, Vector3f)
[Fact]
public void Vector3DotTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float expected = 32.0f;
float actual;
actual = Vector3.Dot(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Dot did not return the expected value.");
}
// A test for Dot (Vector3f, Vector3f)
// Dot test for perpendicular vector
[Fact]
public void Vector3DotTest1()
{
Vector3 a = new Vector3(1.55f, 1.55f, 1);
Vector3 b = new Vector3(2.5f, 3, 1.5f);
Vector3 c = Vector3.Cross(a, b);
float expected = 0.0f;
float actual1 = Vector3.Dot(a, c);
float actual2 = Vector3.Dot(b, c);
Assert.True(MathHelper.Equal(expected, actual1), "Vector3f.Dot did not return the expected value.");
Assert.True(MathHelper.Equal(expected, actual2), "Vector3f.Dot did not return the expected value.");
}
// A test for Length ()
[Fact]
public void Vector3LengthTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float z = 3.0f;
Vector3 target = new Vector3(a, z);
float expected = (float)System.Math.Sqrt(14.0f);
float actual;
actual = target.Length();
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Length did not return the expected value.");
}
// A test for Length ()
// Length test where length is zero
[Fact]
public void Vector3LengthTest1()
{
Vector3 target = new Vector3();
float expected = 0.0f;
float actual = target.Length();
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Length did not return the expected value.");
}
// A test for LengthSquared ()
[Fact]
public void Vector3LengthSquaredTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float z = 3.0f;
Vector3 target = new Vector3(a, z);
float expected = 14.0f;
float actual;
actual = target.LengthSquared();
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.LengthSquared did not return the expected value.");
}
// A test for Min (Vector3f, Vector3f)
[Fact]
public void Vector3MinTest()
{
Vector3 a = new Vector3(-1.0f, 4.0f, -3.0f);
Vector3 b = new Vector3(2.0f, 1.0f, -1.0f);
Vector3 expected = new Vector3(-1.0f, 1.0f, -3.0f);
Vector3 actual;
actual = Vector3.Min(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Min did not return the expected value.");
}
// A test for Max (Vector3f, Vector3f)
[Fact]
public void Vector3MaxTest()
{
Vector3 a = new Vector3(-1.0f, 4.0f, -3.0f);
Vector3 b = new Vector3(2.0f, 1.0f, -1.0f);
Vector3 expected = new Vector3(2.0f, 4.0f, -1.0f);
Vector3 actual;
actual = Vector3.Max(a, b);
Assert.True(MathHelper.Equal(expected, actual), "vector3.Max did not return the expected value.");
}
[Fact]
public void Vector3MinMaxCodeCoverageTest()
{
Vector3 min = Vector3.Zero;
Vector3 max = Vector3.One;
Vector3 actual;
// Min.
actual = Vector3.Min(min, max);
Assert.Equal(actual, min);
actual = Vector3.Min(max, min);
Assert.Equal(actual, min);
// Max.
actual = Vector3.Max(min, max);
Assert.Equal(actual, max);
actual = Vector3.Max(max, min);
Assert.Equal(actual, max);
}
// A test for Lerp (Vector3f, Vector3f, float)
[Fact]
public void Vector3LerpTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 0.5f;
Vector3 expected = new Vector3(2.5f, 3.5f, 4.5f);
Vector3 actual;
actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3f, Vector3f, float)
// Lerp test with factor zero
[Fact]
public void Vector3LerpTest1()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 0.0f;
Vector3 expected = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3f, Vector3f, float)
// Lerp test with factor one
[Fact]
public void Vector3LerpTest2()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 1.0f;
Vector3 expected = new Vector3(4.0f, 5.0f, 6.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3f, Vector3f, float)
// Lerp test with factor > 1
[Fact]
public void Vector3LerpTest3()
{
Vector3 a = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 2.0f;
Vector3 expected = new Vector3(8.0f, 10.0f, 12.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3f, Vector3f, float)
// Lerp test with factor < 0
[Fact]
public void Vector3LerpTest4()
{
Vector3 a = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = -2.0f;
Vector3 expected = new Vector3(-8.0f, -10.0f, -12.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3f, Vector3f, float)
// Lerp test from the same point
[Fact]
public void Vector3LerpTest5()
{
Vector3 a = new Vector3(1.68f, 2.34f, 5.43f);
Vector3 b = a;
float t = 0.18f;
Vector3 expected = new Vector3(1.68f, 2.34f, 5.43f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Reflect (Vector3f, Vector3f)
[Fact]
public void Vector3ReflectTest()
{
Vector3 a = Vector3.Normalize(new Vector3(1.0f, 1.0f, 1.0f));
// Reflect on XZ plane.
Vector3 n = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 expected = new Vector3(a.X, -a.Y, a.Z);
Vector3 actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
// Reflect on XY plane.
n = new Vector3(0.0f, 0.0f, 1.0f);
expected = new Vector3(a.X, a.Y, -a.Z);
actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
// Reflect on YZ plane.
n = new Vector3(1.0f, 0.0f, 0.0f);
expected = new Vector3(-a.X, a.Y, a.Z);
actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector3f, Vector3f)
// Reflection when normal and source are the same
[Fact]
public void Vector3ReflectTest1()
{
Vector3 n = new Vector3(0.45f, 1.28f, 0.86f);
n = Vector3.Normalize(n);
Vector3 a = n;
Vector3 expected = -n;
Vector3 actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector3f, Vector3f)
// Reflection when normal and source are negation
[Fact]
public void Vector3ReflectTest2()
{
Vector3 n = new Vector3(0.45f, 1.28f, 0.86f);
n = Vector3.Normalize(n);
Vector3 a = -n;
Vector3 expected = n;
Vector3 actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector3f, Vector3f)
// Reflection when normal and source are perpendicular (a dot n = 0)
[Fact]
public void Vector3ReflectTest3()
{
Vector3 n = new Vector3(0.45f, 1.28f, 0.86f);
Vector3 temp = new Vector3(1.28f, 0.45f, 0.01f);
// find a perpendicular vector of n
Vector3 a = Vector3.Cross(temp, n);
Vector3 expected = a;
Vector3 actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
}
// A test for Transform(Vector3f, Matrix4x4)
[Fact]
public void Vector3TransformTest()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector3 expected = new Vector3(12.191987f, 21.533493f, 32.616024f);
Vector3 actual;
actual = Vector3.Transform(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value.");
}
// A test for Clamp (Vector3f, Vector3f, Vector3f)
[Fact]
public void Vector3ClampTest()
{
Vector3 a = new Vector3(0.5f, 0.3f, 0.33f);
Vector3 min = new Vector3(0.0f, 0.1f, 0.13f);
Vector3 max = new Vector3(1.0f, 1.1f, 1.13f);
// Normal case.
// Case N1: specfied value is in the range.
Vector3 expected = new Vector3(0.5f, 0.3f, 0.33f);
Vector3 actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// Normal case.
// Case N2: specfied value is bigger than max value.
a = new Vector3(2.0f, 3.0f, 4.0f);
expected = max;
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// Case N3: specfied value is smaller than max value.
a = new Vector3(-2.0f, -3.0f, -4.0f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// Case N4: combination case.
a = new Vector3(-2.0f, 0.5f, 4.0f);
expected = new Vector3(min.X, a.Y, max.Z);
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// User specfied min value is bigger than max value.
max = new Vector3(0.0f, 0.1f, 0.13f);
min = new Vector3(1.0f, 1.1f, 1.13f);
// Case W1: specfied value is in the range.
a = new Vector3(0.5f, 0.3f, 0.33f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// Normal case.
// Case W2: specfied value is bigger than max and min value.
a = new Vector3(2.0f, 3.0f, 4.0f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// Case W3: specfied value is smaller than min and max value.
a = new Vector3(-2.0f, -3.0f, -4.0f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
}
// A test for TransformNormal (Vector3f, Matrix4x4)
[Fact]
public void Vector3TransformNormalTest()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector3 expected = new Vector3(2.19198728f, 1.53349364f, 2.61602545f);
Vector3 actual;
actual = Vector3.TransformNormal(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.TransformNormal did not return the expected value.");
}
// A test for Transform (Vector3f, Quaternion)
[Fact]
public void Vector3TransformByQuaternionTest()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
Quaternion q = Quaternion.CreateFromRotationMatrix(m);
Vector3 expected = Vector3.Transform(v, m);
Vector3 actual = Vector3.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value.");
}
// A test for Transform (Vector3f, Quaternion)
// Transform vector3 with zero quaternion
[Fact]
public void Vector3TransformByQuaternionTest1()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Quaternion q = new Quaternion();
Vector3 expected = v;
Vector3 actual = Vector3.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value.");
}
// A test for Transform (Vector3f, Quaternion)
// Transform vector3 with identity quaternion
[Fact]
public void Vector3TransformByQuaternionTest2()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Quaternion q = Quaternion.Identity;
Vector3 expected = v;
Vector3 actual = Vector3.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value.");
}
// A test for Normalize (Vector3f)
[Fact]
public void Vector3NormalizeTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(
0.26726124191242438468455348087975f,
0.53452248382484876936910696175951f,
0.80178372573727315405366044263926f);
Vector3 actual;
actual = Vector3.Normalize(a);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Normalize did not return the expected value.");
}
// A test for Normalize (Vector3f)
// Normalize vector of length one
[Fact]
public void Vector3NormalizeTest1()
{
Vector3 a = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 expected = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 actual = Vector3.Normalize(a);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Normalize did not return the expected value.");
}
// A test for Normalize (Vector3f)
// Normalize vector of length zero
[Fact]
public void Vector3NormalizeTest2()
{
Vector3 a = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 expected = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 actual = Vector3.Normalize(a);
Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z), "Vector3f.Normalize did not return the expected value.");
}
// A test for operator - (Vector3f)
[Fact]
public void Vector3UnaryNegationTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(-1.0f, -2.0f, -3.0f);
Vector3 actual;
actual = -a;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator - did not return the expected value.");
}
[Fact]
public void Vector3UnaryNegationTest1()
{
Vector3 a = -new Vector3(Single.NaN, Single.PositiveInfinity, Single.NegativeInfinity);
Vector3 b = -new Vector3(0.0f, 0.0f, 0.0f);
Assert.Equal(Single.NaN, a.X);
Assert.Equal(Single.NegativeInfinity, a.Y);
Assert.Equal(Single.PositiveInfinity, a.Z);
Assert.Equal(0.0f, b.X);
Assert.Equal(0.0f, b.Y);
Assert.Equal(0.0f, b.Z);
}
// A test for operator - (Vector3f, Vector3f)
[Fact]
public void Vector3SubtractionTest()
{
Vector3 a = new Vector3(4.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 5.0f, 7.0f);
Vector3 expected = new Vector3(3.0f, -3.0f, -4.0f);
Vector3 actual;
actual = a - b;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator - did not return the expected value.");
}
// A test for operator * (Vector3f, float)
[Fact]
public void Vector3MultiplyTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
float factor = 2.0f;
Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f);
Vector3 actual;
actual = a * factor;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator * did not return the expected value.");
}
// A test for operator * (Vector3f, Vector3f)
[Fact]
public void Vector3MultiplyTest1()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
Vector3 expected = new Vector3(4.0f, 10.0f, 18.0f);
Vector3 actual;
actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator * did not return the expected value.");
}
// A test for operator / (Vector3f, float)
[Fact]
public void Vector3DivisionTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
float div = 2.0f;
Vector3 expected = new Vector3(0.5f, 1.0f, 1.5f);
Vector3 actual;
actual = a / div;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator / did not return the expected value.");
}
// A test for operator / (Vector3f, Vector3f)
[Fact]
public void Vector3DivisionTest1()
{
Vector3 a = new Vector3(4.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 5.0f, 6.0f);
Vector3 expected = new Vector3(4.0f, 0.4f, 0.5f);
Vector3 actual;
actual = a / b;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator / did not return the expected value.");
}
// A test for operator / (Vector3f, Vector3f)
// Divide by zero
[Fact]
public void Vector3DivisionTest2()
{
Vector3 a = new Vector3(-2.0f, 3.0f, float.MaxValue);
float div = 0.0f;
Vector3 actual = a / div;
Assert.True(float.IsNegativeInfinity(actual.X), "Vector3f.operator / did not return the expected value.");
Assert.True(float.IsPositiveInfinity(actual.Y), "Vector3f.operator / did not return the expected value.");
Assert.True(float.IsPositiveInfinity(actual.Z), "Vector3f.operator / did not return the expected value.");
}
// A test for operator / (Vector3f, Vector3f)
// Divide by zero
[Fact]
public void Vector3DivisionTest3()
{
Vector3 a = new Vector3(0.047f, -3.0f, float.NegativeInfinity);
Vector3 b = new Vector3();
Vector3 actual = a / b;
Assert.True(float.IsPositiveInfinity(actual.X), "Vector3f.operator / did not return the expected value.");
Assert.True(float.IsNegativeInfinity(actual.Y), "Vector3f.operator / did not return the expected value.");
Assert.True(float.IsNegativeInfinity(actual.Z), "Vector3f.operator / did not return the expected value.");
}
// A test for operator + (Vector3f, Vector3f)
[Fact]
public void Vector3AdditionTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
Vector3 expected = new Vector3(5.0f, 7.0f, 9.0f);
Vector3 actual;
actual = a + b;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator + did not return the expected value.");
}
// A test for Vector3f (float, float, float)
[Fact]
public void Vector3ConstructorTest()
{
float x = 1.0f;
float y = 2.0f;
float z = 3.0f;
Vector3 target = new Vector3(x, y, z);
Assert.True(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y) && MathHelper.Equal(target.Z, z), "Vector3f.constructor (x,y,z) did not return the expected value.");
}
// A test for Vector3f (Vector2f, float)
[Fact]
public void Vector3ConstructorTest1()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float z = 3.0f;
Vector3 target = new Vector3(a, z);
Assert.True(MathHelper.Equal(target.X, a.X) && MathHelper.Equal(target.Y, a.Y) && MathHelper.Equal(target.Z, z), "Vector3f.constructor (Vector2f,z) did not return the expected value.");
}
// A test for Vector3f ()
// Constructor with no parameter
[Fact]
public void Vector3ConstructorTest3()
{
Vector3 a = new Vector3();
Assert.Equal(a.X, 0.0f);
Assert.Equal(a.Y, 0.0f);
Assert.Equal(a.Z, 0.0f);
}
// A test for Vector2f (float, float)
// Constructor with special floating values
[Fact]
public void Vector3ConstructorTest4()
{
Vector3 target = new Vector3(float.NaN, float.MaxValue, float.PositiveInfinity);
Assert.True(float.IsNaN(target.X), "Vector3f.constructor (Vector3f) did not return the expected value.");
Assert.True(float.Equals(float.MaxValue, target.Y), "Vector3f.constructor (Vector3f) did not return the expected value.");
Assert.True(float.IsPositiveInfinity(target.Z), "Vector3f.constructor (Vector3f) did not return the expected value.");
}
// A test for Add (Vector3f, Vector3f)
[Fact]
public void Vector3AddTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(5.0f, 6.0f, 7.0f);
Vector3 expected = new Vector3(6.0f, 8.0f, 10.0f);
Vector3 actual;
actual = Vector3.Add(a, b);
Assert.Equal(expected, actual);
}
// A test for Divide (Vector3f, float)
[Fact]
public void Vector3DivideTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
float div = 2.0f;
Vector3 expected = new Vector3(0.5f, 1.0f, 1.5f);
Vector3 actual;
actual = Vector3.Divide(a, div);
Assert.Equal(expected, actual);
}
// A test for Divide (Vector3f, Vector3f)
[Fact]
public void Vector3DivideTest1()
{
Vector3 a = new Vector3(1.0f, 6.0f, 7.0f);
Vector3 b = new Vector3(5.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(1.0f / 5.0f, 6.0f / 2.0f, 7.0f / 3.0f);
Vector3 actual;
actual = Vector3.Divide(a, b);
Assert.Equal(expected, actual);
}
// A test for Equals (object)
[Fact]
public void Vector3EqualsTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare between different types.
obj = new Quaternion();
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
}
// A test for Multiply (Vector3f, float)
[Fact]
public void Vector3MultiplyTest2()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
float factor = 2.0f;
Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f);
Vector3 actual = Vector3.Multiply(a, factor);
Assert.Equal(expected, actual);
}
// A test for Multiply (Vector3f, Vector3f)
[Fact]
public void Vector3MultiplyTest3()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(5.0f, 6.0f, 7.0f);
Vector3 expected = new Vector3(5.0f, 12.0f, 21.0f);
Vector3 actual;
actual = Vector3.Multiply(a, b);
Assert.Equal(expected, actual);
}
// A test for Negate (Vector3f)
[Fact]
public void Vector3NegateTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(-1.0f, -2.0f, -3.0f);
Vector3 actual;
actual = Vector3.Negate(a);
Assert.Equal(expected, actual);
}
// A test for operator != (Vector3f, Vector3f)
[Fact]
public void Vector3InequalityTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = true;
actual = a != b;
Assert.Equal(expected, actual);
}
// A test for operator == (Vector3f, Vector3f)
[Fact]
public void Vector3EqualityTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a == b;
Assert.Equal(expected, actual);
}
// A test for Subtract (Vector3f, Vector3f)
[Fact]
public void Vector3SubtractTest()
{
Vector3 a = new Vector3(1.0f, 6.0f, 3.0f);
Vector3 b = new Vector3(5.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(-4.0f, 4.0f, 0.0f);
Vector3 actual;
actual = Vector3.Subtract(a, b);
Assert.Equal(expected, actual);
}
// A test for One
[Fact]
public void Vector3OneTest()
{
Vector3 val = new Vector3(1.0f, 1.0f, 1.0f);
Assert.Equal(val, Vector3.One);
}
// A test for UnitX
[Fact]
public void Vector3UnitXTest()
{
Vector3 val = new Vector3(1.0f, 0.0f, 0.0f);
Assert.Equal(val, Vector3.UnitX);
}
// A test for UnitY
[Fact]
public void Vector3UnitYTest()
{
Vector3 val = new Vector3(0.0f, 1.0f, 0.0f);
Assert.Equal(val, Vector3.UnitY);
}
// A test for UnitZ
[Fact]
public void Vector3UnitZTest()
{
Vector3 val = new Vector3(0.0f, 0.0f, 1.0f);
Assert.Equal(val, Vector3.UnitZ);
}
// A test for Zero
[Fact]
public void Vector3ZeroTest()
{
Vector3 val = new Vector3(0.0f, 0.0f, 0.0f);
Assert.Equal(val, Vector3.Zero);
}
// A test for Equals (Vector3f)
[Fact]
public void Vector3EqualsTest1()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a.Equals(b);
Assert.Equal(expected, actual);
}
// A test for Vector3f (float)
[Fact]
public void Vector3ConstructorTest5()
{
float value = 1.0f;
Vector3 target = new Vector3(value);
Vector3 expected = new Vector3(value, value, value);
Assert.Equal(expected, target);
value = 2.0f;
target = new Vector3(value);
expected = new Vector3(value, value, value);
Assert.Equal(expected, target);
}
// A test for Vector3f comparison involving NaN values
[Fact]
public void Vector3EqualsNanTest()
{
Vector3 a = new Vector3(float.NaN, 0, 0);
Vector3 b = new Vector3(0, float.NaN, 0);
Vector3 c = new Vector3(0, 0, float.NaN);
Assert.False(a == Vector3.Zero);
Assert.False(b == Vector3.Zero);
Assert.False(c == Vector3.Zero);
Assert.True(a != Vector3.Zero);
Assert.True(b != Vector3.Zero);
Assert.True(c != Vector3.Zero);
Assert.False(a.Equals(Vector3.Zero));
Assert.False(b.Equals(Vector3.Zero));
Assert.False(c.Equals(Vector3.Zero));
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.False(a.Equals(a));
Assert.False(b.Equals(b));
Assert.False(c.Equals(c));
}
[Fact]
public void Vector3AbsTest()
{
Vector3 v1 = new Vector3(-2.5f, 2.0f, 0.5f);
Vector3 v3 = Vector3.Abs(new Vector3(0.0f, Single.NegativeInfinity, Single.NaN));
Vector3 v = Vector3.Abs(v1);
Assert.Equal(2.5f, v.X);
Assert.Equal(2.0f, v.Y);
Assert.Equal(0.5f, v.Z);
Assert.Equal(0.0f, v3.X);
Assert.Equal(Single.PositiveInfinity, v3.Y);
Assert.Equal(Single.NaN, v3.Z);
}
[Fact]
public void Vector3SqrtTest()
{
Vector3 a = new Vector3(-2.5f, 2.0f, 0.5f);
Vector3 b = new Vector3(5.5f, 4.5f, 16.5f);
Assert.Equal(2, (int)Vector3.SquareRoot(b).X);
Assert.Equal(2, (int)Vector3.SquareRoot(b).Y);
Assert.Equal(4, (int)Vector3.SquareRoot(b).Z);
Assert.Equal(Single.NaN, Vector3.SquareRoot(a).X);
}
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[Fact]
public unsafe void Vector3SizeofTest()
{
Assert.Equal(12, sizeof(Vector3));
Assert.Equal(24, sizeof(Vector3_2x));
Assert.Equal(16, sizeof(Vector3PlusFloat));
Assert.Equal(32, sizeof(Vector3PlusFloat_2x));
}
[StructLayout(LayoutKind.Sequential)]
struct Vector3_2x
{
Vector3 a;
Vector3 b;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector3PlusFloat
{
Vector3 v;
float f;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector3PlusFloat_2x
{
Vector3PlusFloat a;
Vector3PlusFloat b;
}
[Fact]
public void SetFieldsTest()
{
Vector3 v3 = new Vector3(4f, 5f, 6f);
v3.X = 1.0f;
v3.Y = 2.0f;
v3.Z = 3.0f;
Assert.Equal(1.0f, v3.X);
Assert.Equal(2.0f, v3.Y);
Assert.Equal(3.0f, v3.Z);
Vector3 v4 = v3;
v4.Y = 0.5f;
v4.Z = 2.2f;
Assert.Equal(1.0f, v4.X);
Assert.Equal(0.5f, v4.Y);
Assert.Equal(2.2f, v4.Z);
Assert.Equal(2.0f, v3.Y);
Vector3 before = new Vector3(1f, 2f, 3f);
Vector3 after = before;
after.X = 500.0f;
Assert.NotEqual(before, after);
}
[Fact]
public void EmbeddedVectorSetFields()
{
EmbeddedVectorObject evo = new EmbeddedVectorObject();
evo.FieldVector.X = 5.0f;
evo.FieldVector.Y = 5.0f;
evo.FieldVector.Z = 5.0f;
Assert.Equal(5.0f, evo.FieldVector.X);
Assert.Equal(5.0f, evo.FieldVector.Y);
Assert.Equal(5.0f, evo.FieldVector.Z);
}
private class EmbeddedVectorObject
{
public Vector3 FieldVector;
}
}
}
| |
// 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;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class UShortKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClass_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalStatement_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalVariableDeclaration_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStackAlloc()
{
VerifyKeyword(
@"class C {
int* foo = stackalloc $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InFixedStatement()
{
VerifyKeyword(
@"fixed ($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InDelegateReturnType()
{
VerifyKeyword(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCastType()
{
VerifyKeyword(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCastType2()
{
VerifyKeyword(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOuterConst()
{
VerifyKeyword(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterInnerConst()
{
VerifyKeyword(AddInsideMethod(
@"const $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InEmptyStatement()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void EnumBaseTypes()
{
VerifyKeyword(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType1()
{
VerifyKeyword(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType2()
{
VerifyKeyword(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType3()
{
VerifyKeyword(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType4()
{
VerifyKeyword(AddInsideMethod(
@"IList<IFoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInBaseList()
{
VerifyAbsence(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType_InBaseList()
{
VerifyKeyword(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIs()
{
VerifyKeyword(AddInsideMethod(
@"var v = foo is $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAs()
{
VerifyKeyword(AddInsideMethod(
@"var v = foo as $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethod()
{
VerifyKeyword(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterField()
{
VerifyKeyword(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterProperty()
{
VerifyKeyword(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAttribute()
{
VerifyKeyword(
@"class C {
[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideStruct()
{
VerifyKeyword(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideInterface()
{
VerifyKeyword(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideClass()
{
VerifyKeyword(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPartial()
{
VerifyAbsence(@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedPartial()
{
VerifyAbsence(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAbstract()
{
VerifyKeyword(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedInternal()
{
VerifyKeyword(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedStaticPublic()
{
VerifyKeyword(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPublicStatic()
{
VerifyKeyword(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterVirtualPublic()
{
VerifyKeyword(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPublic()
{
VerifyKeyword(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPrivate()
{
VerifyKeyword(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedProtected()
{
VerifyKeyword(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedSealed()
{
VerifyKeyword(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedStatic()
{
VerifyKeyword(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InLocalVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InForVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"for ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InForeachVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"foreach ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InUsingVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"using ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InFromVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"var q = from $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InJoinVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"var q = from a in b
join $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodOpenParen()
{
VerifyKeyword(
@"class C {
void Foo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodComma()
{
VerifyKeyword(
@"class C {
void Foo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodAttribute()
{
VerifyKeyword(
@"class C {
void Foo(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorOpenParen()
{
VerifyKeyword(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorComma()
{
VerifyKeyword(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorAttribute()
{
VerifyKeyword(
@"class C {
public C(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateOpenParen()
{
VerifyKeyword(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateComma()
{
VerifyKeyword(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateAttribute()
{
VerifyKeyword(
@"delegate void D(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterThis()
{
VerifyKeyword(
@"static class C {
public static void Foo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterRef()
{
VerifyKeyword(
@"class C {
void Foo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOut()
{
VerifyKeyword(
@"class C {
void Foo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterLambdaRef()
{
VerifyKeyword(
@"class C {
void Foo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterLambdaOut()
{
VerifyKeyword(
@"class C {
void Foo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterParams()
{
VerifyKeyword(
@"class C {
void Foo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InImplicitOperator()
{
VerifyKeyword(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InExplicitOperator()
{
VerifyKeyword(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIndexerBracket()
{
VerifyKeyword(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIndexerBracketComma()
{
VerifyKeyword(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNewInExpression()
{
VerifyKeyword(AddInsideMethod(
@"new $$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InTypeOf()
{
VerifyKeyword(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InDefault()
{
VerifyKeyword(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InSizeOf()
{
VerifyKeyword(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInObjectInitializerMemberContext()
{
VerifyAbsence(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCrefContext()
{
VerifyKeyword(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCrefContextNotAfterDot()
{
VerifyAbsence(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[WorkItem(18374)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAsync()
{
VerifyKeyword(@"class c { async $$ }");
}
[WorkItem(18374)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterAsyncAsType()
{
VerifyAbsence(@"class c { async async $$ }");
}
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInCrefTypeParameter()
{
VerifyAbsence(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GameplayScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Devices.Sensors;
using GameStateManagement;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Devices;
using Microsoft.Xna.Framework.Audio;
#endregion
namespace MarbleMazeGame
{
class GameplayScreen : GameScreen
{
#region Fields
bool gameOver = false;
bool startScreen = true;
TimeSpan startScreenTime = TimeSpan.FromSeconds(4);
Maze maze;
Marble marble;
Camera camera;
LinkedListNode<Vector3> lastCheackpointNode;
public new bool IsActive = true;
readonly float angularVelocity = MathHelper.ToRadians(1.5f);
SpriteFont timeFont;
TimeSpan gameTime;
public Vector3 AccelerometerCalibrationData = Vector3.Zero;
#endregion
#region Initializations
public GameplayScreen()
{
TransitionOnTime = TimeSpan.FromSeconds(0.0);
TransitionOffTime = TimeSpan.FromSeconds(0.0);
// Enable double tap gesture to calibrate the accelerometer
EnabledGestures = GestureType.Tap | GestureType.DoubleTap;
}
#endregion
#region Loading
/// <summary>
/// Load the game content
/// </summary>
public override void LoadContent()
{
timeFont = ScreenManager.Game.Content.Load<SpriteFont>(@"Fonts\MenuFont");
Accelerometer.Initialize();
base.LoadContent();
}
/// <summary>
/// Load all assets for the game
/// </summary>
public void LoadAssets()
{
InitializeCamera();
InitializeMaze();
InitializeMarble();
}
/// <summary>
/// Initialize the camera
/// </summary>
private void InitializeCamera()
{
// Create the camera
camera = new Camera(ScreenManager.Game, ScreenManager.GraphicsDevice);
camera.Initialize();
}
/// <summary>
/// Initialize maze
/// </summary>
private void InitializeMaze()
{
maze = new Maze(ScreenManager.Game)
{
Position = Vector3.Zero,
Camera = camera
};
maze.Initialize();
// Save the last checkpoint
lastCheackpointNode = maze.Checkpoints.First;
}
/// <summary>
/// Initialize the marble
/// </summary>
private void InitializeMarble()
{
marble = new Marble(ScreenManager.Game)
{
Position = maze.StartPoistion,
Camera = camera,
Maze = maze
};
marble.Initialize();
}
#endregion
#region Update
/// <summary>
/// Handle all the input.
/// </summary>
/// <param name="input"></param>
public override void HandleInput(InputState input)
{
if (input == null)
throw new ArgumentNullException("input");
if (input.IsPauseGame(null))
{
if (!gameOver)
PauseCurrentGame();
else
FinishCurrentGame();
}
if (IsActive && !startScreen)
{
if (input.Gestures.Count > 0)
{
GestureSample sample = input.Gestures[0];
if (sample.GestureType == GestureType.Tap)
{
if (gameOver)
FinishCurrentGame();
}
}
if (!gameOver)
{
if (Microsoft.Devices.Environment.DeviceType == DeviceType.Device)
{
// Calibrate the accelerometer upon a double tap
if (input.Gestures.Count > 0)
{
GestureSample sample = input.Gestures[0];
if (sample.GestureType == GestureType.DoubleTap)
{
CalibrateGame();
input.Gestures.Clear();
}
}
}
// Rotate the maze according to accelerometer data
Vector3 currentAccelerometerState = Accelerometer.GetState().Acceleration;
currentAccelerometerState.X -= AccelerometerCalibrationData.X;
currentAccelerometerState.Y -= AccelerometerCalibrationData.Y;
currentAccelerometerState.Z -= AccelerometerCalibrationData.Z;
if (Microsoft.Devices.Environment.DeviceType == DeviceType.Device)
{
//Change the velocity according to acceleration reading
maze.Rotation.Z = (float)Math.Round(MathHelper.ToRadians(currentAccelerometerState.Y * 30), 2);
maze.Rotation.X = -(float)Math.Round(MathHelper.ToRadians(currentAccelerometerState.X * 30), 2);
}
else if (Microsoft.Devices.Environment.DeviceType == DeviceType.Emulator)
{
Vector3 Rotation = Vector3.Zero;
if (currentAccelerometerState.X != 0)
{
if (currentAccelerometerState.X > 0)
Rotation += new Vector3(0, 0, -angularVelocity);
else
Rotation += new Vector3(0, 0, angularVelocity);
}
if (currentAccelerometerState.Y != 0)
{
if (currentAccelerometerState.Y > 0)
Rotation += new Vector3(-angularVelocity, 0, 0);
else
Rotation += new Vector3(angularVelocity, 0, 0);
}
// Limit the rotation of the maze to 30 degrees
maze.Rotation.X =
MathHelper.Clamp(maze.Rotation.X + Rotation.X,
MathHelper.ToRadians(-30), MathHelper.ToRadians(30));
maze.Rotation.Z =
MathHelper.Clamp(maze.Rotation.Z + Rotation.Z,
MathHelper.ToRadians(-30), MathHelper.ToRadians(30));
}
}
}
}
/// <summary>
/// Update all the game component
/// </summary>
/// <param name="gameTime"></param>
/// <param name="otherScreenHasFocus"></param>
/// <param name="coveredByOtherScreen"></param>
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
if (IsActive && !gameOver)
{
if (!startScreen)
{
// Calculate the time from the start of the game
this.gameTime += gameTime.ElapsedGameTime;
CheckFallInPit();
UpdateLastCheackpoint();
}
// Update all the component of the game
maze.Update(gameTime);
marble.Update(gameTime);
camera.Update(gameTime);
CheckGameFinish();
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
}
if (startScreen)
{
if (startScreenTime.Ticks > 0)
{
startScreenTime -= gameTime.ElapsedGameTime;
}
else
{
startScreen = false;
}
}
}
#endregion
#region Render
/// <summary>
/// Draw all the game component
/// </summary>
/// <param name="gameTime"></param>
public override void Draw(GameTime gameTime)
{
ScreenManager.GraphicsDevice.Clear(Color.Black);
ScreenManager.SpriteBatch.Begin();
if (startScreen)
{
DrawStartGame(gameTime);
}
if (IsActive)
{
// Draw the elapsed time
ScreenManager.SpriteBatch.DrawString(timeFont,
String.Format("{0:00}:{1:00}", this.gameTime.Minutes,
this.gameTime.Seconds), new Vector2(20, 20), Color.YellowGreen);
// Drawing sprites changes some render states around, which don't play
// nicely with 3d models.
// In particular, we need to enable the depth buffer.
DepthStencilState depthStensilState =
new DepthStencilState() { DepthBufferEnable = true };
ScreenManager.GraphicsDevice.DepthStencilState = depthStensilState;
// Draw all the game components
maze.Draw(gameTime);
marble.Draw(gameTime);
}
if (gameOver)
{
AudioManager.StopSounds();
DrawEndGame(gameTime);
}
ScreenManager.SpriteBatch.End();
base.Draw(gameTime);
}
private void DrawEndGame(GameTime gameTime)
{
string text = HighScoreScreen.IsInHighscores(this.gameTime) ? " You got a High Score!" :
" Game Over";
text += "\nTouch the screen to continue";
Vector2 size = timeFont.MeasureString(text);
Vector2 textPosition = (new Vector2(ScreenManager.GraphicsDevice.Viewport.Width,
ScreenManager.GraphicsDevice.Viewport.Height) - size) / 2f;
ScreenManager.SpriteBatch.DrawString(timeFont, text,
textPosition, Color.White);
}
private void DrawStartGame(GameTime gameTime)
{
string text = (startScreenTime.Seconds == 0) ? "Go!" : startScreenTime.Seconds.ToString();
Vector2 size = timeFont.MeasureString(text);
Vector2 textPosition = (new Vector2(ScreenManager.GraphicsDevice.Viewport.Width,
ScreenManager.GraphicsDevice.Viewport.Height) - size) / 2f;
ScreenManager.SpriteBatch.DrawString(timeFont, text, textPosition, Color.White);
}
#endregion
#region Private functions
/// <summary>
/// Update the last checkpoint to return to after falling in a pit.
/// </summary>
private void UpdateLastCheackpoint()
{
BoundingSphere marblePosition = marble.BoundingSphereTransformed;
var tmp = lastCheackpointNode;
while (tmp.Next != null)
{
// If the marble is close to a checkpoint save the checkpoint
if (Math.Abs(Vector3.Distance(marblePosition.Center, tmp.Next.Value))
<= marblePosition.Radius * 3)
{
AudioManager.PlaySound("checkpoint");
lastCheackpointNode = tmp.Next;
return;
}
tmp = tmp.Next;
}
}
/// <summary>
/// If marble falls in a pit, return the marble to the last checkpoint
/// the marble passed.
/// </summary>
private void CheckFallInPit()
{
if (marble.Position.Y < -150)
{
marble.Position = lastCheackpointNode.Value;
maze.Rotation = Vector3.Zero;
marble.Acceleration = Vector3.Zero;
marble.Velocity = Vector3.Zero;
}
}
/// <summary>
/// Check if the game has ended.
/// </summary>
private void CheckGameFinish()
{
BoundingSphere marblePosition = marble.BoundingSphereTransformed;
if (Math.Abs(Vector3.Distance(marblePosition.Center, maze.End)) <= marblePosition.Radius * 3)
{
gameOver = true;
return;
}
}
/// <summary>
/// Finish the current game
/// </summary>
private void FinishCurrentGame()
{
IsActive = false;
foreach (GameScreen screen in ScreenManager.GetScreens())
screen.ExitScreen();
if (HighScoreScreen.IsInHighscores(gameTime))
{
// Show the device's keyboard
Guide.BeginShowKeyboardInput(PlayerIndex.One,
"Player Name", "Enter your name (max 15 characters)", "Player", (r) =>
{
string playerName = Guide.EndShowKeyboardInput(r);
if (playerName != null && playerName.Length > 15)
playerName = playerName.Substring(0, 15);
HighScoreScreen.PutHighScore(playerName, gameTime);
ScreenManager.AddScreen(new BackgroundScreen(), null);
ScreenManager.AddScreen(new HighScoreScreen(), null);
}, null);
return;
}
ScreenManager.AddScreen(new BackgroundScreen(), null);
ScreenManager.AddScreen(new HighScoreScreen(), null);
}
/// <summary>
/// Pause the game.
/// </summary>
private void PauseCurrentGame()
{
IsActive = false;
// Pause sounds
AudioManager.PauseResumeSounds(false);
ScreenManager.AddScreen(new BackgroundScreen(), null);
ScreenManager.AddScreen(new PauseScreen(), null);
}
/// <summary>
/// Launch calibration screen.
/// </summary>
private void CalibrateGame()
{
IsActive = false;
// Pause the sounds
AudioManager.PauseResumeSounds(false);
ScreenManager.AddScreen(new BackgroundScreen(), null);
ScreenManager.AddScreen(new CalibrationScreen(this), null);
}
/// <summary>
/// Restart the game.
/// </summary>
internal void Restart()
{
marble.Position = maze.StartPoistion;
marble.Velocity = Vector3.Zero;
marble.Acceleration = Vector3.Zero;
maze.Rotation = Vector3.Zero;
IsActive = true;
gameOver = false;
gameTime = TimeSpan.Zero;
startScreen = true;
startScreenTime = TimeSpan.FromSeconds(4);
lastCheackpointNode = maze.Checkpoints.First;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Abp.App.TestWebAPI.Areas.HelpPage.ModelDescriptions;
using Abp.App.TestWebAPI.Areas.HelpPage.Models;
namespace Abp.App.TestWebAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using HETSAPI.Models;
using HETSAPI.ViewModels;
namespace HETSAPI.Services.Impl
{
/// <summary>
///
/// </summary>
public class UserService : IUserService
{
private readonly DbAppContext _context;
/// <summary>
/// Create a service and set the database context
/// </summary>
public UserService(DbAppContext context)
{
_context = context;
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <response code="201">User created</response>
public virtual IActionResult UsergroupsBulkPostAsync(GroupMembership[] items)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <response code="201">User created</response>
public virtual IActionResult UsersBulkPostAsync(User[] items)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <response code="200">OK</response>
public virtual IActionResult UsersGetAsync()
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of User to delete</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
public virtual IActionResult UsersIdDeletePostAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns a user's favourites of a given context type</remarks>
/// <param name="id">id of User to fetch favorites for</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
public virtual IActionResult UsersIdFavouritesGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of User to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
public virtual IActionResult UsersIdGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns all groups that a user is a member of</remarks>
/// <param name="id">id of User to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
public virtual IActionResult UsersIdGroupsGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Add to the active set of groups for a user</remarks>
/// <param name="id">id of User to update</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
public virtual IActionResult UsersIdGroupsPostAsync(int id, GroupMembershipViewModel item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Updates the active set of groups for a user</remarks>
/// <param name="id">id of User to update</param>
/// <param name="items"></param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
public virtual IActionResult UsersIdGroupsPutAsync(int id, GroupMembershipViewModel[] items)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns the set of permissions for a user</remarks>
/// <param name="id">id of User to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
public virtual IActionResult UsersIdPermissionsGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of User to fetch</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
public virtual IActionResult UsersIdPutAsync(int id, UserViewModel item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns the roles for a user</remarks>
/// <param name="id">id of User to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
public virtual IActionResult UsersIdRolesGetAsync(int id)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Adds a role to a user</remarks>
/// <param name="id">id of User to update</param>
/// <param name="item"></param>
/// <response code="201">Role created for user</response>
public virtual IActionResult UsersIdRolesPostAsync(int id, UserRoleViewModel item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Updates the roles for a user</remarks>
/// <param name="id">id of User to update</param>
/// <param name="items"></param>
/// <response code="200">OK</response>
/// <response code="404">User not found</response>
public virtual IActionResult UsersIdRolesPutAsync(int id, UserRoleViewModel[] items)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <response code="201">User created</response>
public virtual IActionResult UsersPostAsync(UserViewModel item)
{
var result = "";
return new ObjectResult(result);
}
/// <summary>
/// Searches Users
/// </summary>
/// <remarks>Used to search users.</remarks>
/// <param name="districts">Districts (comma seperated list of id numbers)</param>
/// <param name="surname"></param>
/// <param name="includeInactive">True if Inactive users will be returned</param>
/// <response code="200">OK</response>
public virtual IActionResult UsersSearchGetAsync(string districts, string surname, bool? includeInactive)
{
var result = "";
return new ObjectResult(result);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Net.Test.Common;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
[PlatformSpecific(TestPlatforms.Windows)] // NegotiateStream only supports client-side functionality on Unix
public abstract class NegotiateStreamStreamToStreamTest
{
private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
protected abstract Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName);
protected abstract Task AuthenticateAsServerAsync(NegotiateStream server);
[Fact]
public void NegotiateStream_StreamToStream_Authentication_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(false, serverIdentity.IsAuthenticated);
Assert.Equal("", serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[Fact]
public void NegotiateStream_StreamToStream_Authentication_TargetName_Success()
{
string targetName = "testTargetName";
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, targetName);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[Fact]
public void NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails()
{
string targetName = "testTargetName";
// Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a
// NetworkCredential object with empty user, password and domain.
NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", "");
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials);
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials);
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, emptyNetworkCredential, targetName);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
// TODO #5241: Behavior difference:
Assert.Equal(false, clientIdentity.IsAuthenticated);
// On .Net Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertHasName(clientIdentity, @"NT AUTHORITY\ANONYMOUS LOGON");
}
}
[Fact]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Sync_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
[Fact]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Async_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
[Fact]
public void NegotiateStream_StreamToStream_Flush_Propagated()
{
VirtualNetwork network = new VirtualNetwork();
using (var stream = new VirtualNetworkStream(network, isServer: false))
using (var negotiateStream = new NegotiateStream(stream))
{
Assert.False(stream.HasBeenSyncFlushed);
negotiateStream.Flush();
Assert.True(stream.HasBeenSyncFlushed);
}
}
[Fact]
public void NegotiateStream_StreamToStream_FlushAsync_Propagated()
{
VirtualNetwork network = new VirtualNetwork();
using (var stream = new VirtualNetworkStream(network, isServer: false))
using (var negotiateStream = new NegotiateStream(stream))
{
Task task = negotiateStream.FlushAsync();
Assert.False(task.IsCompleted);
stream.CompleteAsyncFlush();
Assert.True(task.IsCompleted);
}
}
}
public sealed class NegotiateStreamStreamToStreamTest_Async : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
client.AuthenticateAsClientAsync(credential, targetName);
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
server.AuthenticateAsServerAsync();
}
public sealed class NegotiateStreamStreamToStreamTest_BeginEnd : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
Task.Factory.FromAsync(client.BeginAuthenticateAsClient, client.EndAuthenticateAsClient, credential, targetName, null);
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
Task.Factory.FromAsync(server.BeginAuthenticateAsServer, server.EndAuthenticateAsServer, null);
}
public sealed class NegotiateStreamStreamToStreamTest_Sync : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
Task.Run(() => client.AuthenticateAsClient(credential, targetName));
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
Task.Run(() => server.AuthenticateAsServer());
}
}
| |
// Copyright (c) 2011 Smarkets Limited
//
// 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.Net.Security;
using System.Net.Sockets;
using System.IO;
using log4net;
using ProtoBuf;
using IronSmarkets.Exceptions;
using IronSmarkets.Proto.Seto;
namespace IronSmarkets.Sockets
{
internal sealed class SessionSocket : IDisposable, ISocket<Payload>
{
private static readonly ILog Log = LogManager.GetLogger(typeof(SessionSocket));
private readonly ISocketSettings _settings;
private readonly TcpClient _client = new TcpClient();
private bool _disposed;
private Stream _tcpStream;
public Stream TcpStream { get { return _tcpStream; } }
public bool IsConnected
{
get
{
return _client.Connected;
}
}
public SessionSocket(ISocketSettings settings)
{
_settings = settings;
}
~SessionSocket()
{
Dispose(false);
}
public void Connect()
{
if (_disposed)
throw new ObjectDisposedException(
"SessionSocket",
"Called Connect on disposed object");
if (IsConnected)
throw new ConnectionException(
"Socket already connected");
if (Log.IsDebugEnabled) Log.Debug(
string.Format(
"Connecting to host {0} on port {1}",
_settings.Host, _settings.Port));
_client.Connect(_settings.Host, _settings.Port);
_client.Client.NoDelay = true;
if (_settings.Ssl)
{
if (Log.IsDebugEnabled) Log.Debug(
"Wrapping stream with SSL");
var sslStream = new SslStream(
_client.GetStream(), false,
_settings.RemoteSslCallback, null);
if (Log.IsDebugEnabled) Log.Debug(
string.Format(
"Validating hostname {0}", _settings.Hostname));
sslStream.AuthenticateAsClient(_settings.Hostname);
_tcpStream = new SafeSslStream(sslStream);
}
else
{
_tcpStream = _client.GetStream();
}
if (Log.IsDebugEnabled) Log.Debug(
"Connection established; stream is ready");
}
public void Disconnect()
{
if (_disposed)
throw new ObjectDisposedException(
"SessionSocket",
"Called Disconnect on disposed object");
if (IsConnected)
{
if (Log.IsDebugEnabled) Log.Debug("Closing TCP stream");
_tcpStream.Close();
if (Log.IsDebugEnabled) Log.Debug("Closing TCP client");
_client.Close();
}
}
public void Write(Payload payload)
{
if (_disposed)
throw new ObjectDisposedException(
"SessionSocket",
"Called Write on disposed object");
if (!IsConnected)
throw new ConnectionException(
"Socket not connected");
if (Log.IsDebugEnabled) Log.Debug(
string.Format(
"Serializing payload [out:{0}] {1} / {2} with length prefix",
payload.EtoPayload.Seq, payload.Type,
payload.EtoPayload.Type));
Serializer.SerializeWithLengthPrefix(
TcpStream, payload, PrefixStyle.Base128);
}
public void Flush()
{
if (_disposed)
throw new ObjectDisposedException(
"SessionSocket",
"Called Flush on disposed object");
if (!IsConnected)
throw new ConnectionException(
"Socket not connected");
// This may be a useless. From MSDN:
// The Flush method implements the Stream.Flush method;
// however, because NetworkStream is not buffered, it has
// no affect on network streams. Calling the Flush method
// does not throw an exception.
if (Log.IsDebugEnabled) Log.Debug("Flushing network stream");
TcpStream.Flush();
}
public Payload Read()
{
if (_disposed)
throw new ObjectDisposedException(
"SessionSocket",
"Called Read on disposed object");
if (!IsConnected)
throw new ConnectionException(
"Socket not connected");
var payload = Serializer.DeserializeWithLengthPrefix<Payload>(
TcpStream, PrefixStyle.Base128);
if (Log.IsDebugEnabled)
{
if (payload != null)
{
Log.Debug(
string.Format(
"Deserialized payload [in:{0}] {1} / {2}",
payload.EtoPayload.Seq, payload.Type,
payload.EtoPayload.Type));
}
else
{
Log.Debug("Deserialized null payload");
}
}
return payload;
}
private void Dispose(bool disposing)
{
if (_disposed)
return;
try
{
if (disposing)
{
Disconnect();
}
}
finally
{
_disposed = true;
}
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| |
// <copyright file="UserCholeskyTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 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>
using MathNet.Numerics.LinearAlgebra;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Factorization
{
/// <summary>
/// Cholesky factorization tests for a user matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class UserCholeskyTests
{
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = UserDefinedMatrix.Identity(order);
var factorC = matrixI.Cholesky().Factor;
Assert.AreEqual(matrixI.RowCount, factorC.RowCount);
Assert.AreEqual(matrixI.ColumnCount, factorC.ColumnCount);
for (var i = 0; i < factorC.RowCount; i++)
{
for (var j = 0; j < factorC.ColumnCount; j++)
{
Assert.AreEqual(i == j ? 1.0 : 0.0, factorC[i, j]);
}
}
}
/// <summary>
/// Cholesky factorization fails with diagonal a non-positive definite matrix.
/// </summary>
[Test]
public void CholeskyFailsWithDiagonalNonPositiveDefiniteMatrix()
{
var matrixI = UserDefinedMatrix.Identity(10);
matrixI[3, 3] = -4.0f;
Assert.That(() => matrixI.Cholesky(), Throws.ArgumentException);
}
/// <summary>
/// Cholesky factorization fails with a non-square matrix.
/// </summary>
[Test]
public void CholeskyFailsWithNonSquareMatrix()
{
var matrixI = new UserDefinedMatrix(3, 2);
Assert.That(() => matrixI.Cholesky(), Throws.ArgumentException);
}
/// <summary>
/// Identity determinant is one.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void IdentityDeterminantIsOne(int order)
{
var matrixI = UserDefinedMatrix.Identity(order);
var factorC = matrixI.Cholesky();
Assert.AreEqual(1.0, factorC.Determinant);
Assert.AreEqual(0.0, factorC.DeterminantLn);
}
/// <summary>
/// Can factorize a random square matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanFactorizeRandomMatrix(int order)
{
var matrixX = new UserDefinedMatrix(Matrix<float>.Build.RandomPositiveDefinite(order, 1).ToArray());
var chol = matrixX.Cholesky();
var factorC = chol.Factor;
// Make sure the Cholesky factor has the right dimensions.
Assert.AreEqual(order, factorC.RowCount);
Assert.AreEqual(order, factorC.ColumnCount);
// Make sure the Cholesky factor is lower triangular.
for (var i = 0; i < factorC.RowCount; i++)
{
for (var j = i + 1; j < factorC.ColumnCount; j++)
{
Assert.AreEqual(0.0, factorC[i, j]);
}
}
// Make sure the cholesky factor times it's transpose is the original matrix.
var matrixXfromC = factorC * factorC.Transpose();
for (var i = 0; i < matrixXfromC.RowCount; i++)
{
for (var j = 0; j < matrixXfromC.ColumnCount; j++)
{
Assert.AreEqual(matrixX[i, j], matrixXfromC[i, j], 1e-3);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVector(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.RandomPositiveDefinite(order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var chol = matrixA.Cholesky();
var b = new UserDefinedVector(Vector<float>.Build.Random(order, 1).ToArray());
var x = chol.Solve(b);
Assert.AreEqual(b.Count, x.Count);
var matrixBReconstruct = matrixA * x;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(b[i], matrixBReconstruct[i], 0.5);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="col">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 4)]
[TestCase(5, 8)]
[TestCase(10, 3)]
[TestCase(50, 10)]
[TestCase(100, 100)]
public void CanSolveForRandomMatrix(int row, int col)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.RandomPositiveDefinite(row, 1).ToArray());
var matrixACopy = matrixA.Clone();
var chol = matrixA.Cholesky();
var matrixB = new UserDefinedMatrix(Matrix<float>.Build.Random(row, col, 1).ToArray());
var matrixX = chol.Solve(matrixB);
Assert.AreEqual(matrixB.RowCount, matrixX.RowCount);
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.RandomPositiveDefinite(order, 1).ToArray());
var matrixACopy = matrixA.Clone();
var chol = matrixA.Cholesky();
var b = new UserDefinedVector(Vector<float>.Build.Random(order, 1).ToArray());
var matrixBCopy = b.Clone();
var x = new UserDefinedVector(order);
chol.Solve(b, x);
Assert.AreEqual(b.Count, x.Count);
var matrixBReconstruct = matrixA * x;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(b[i], matrixBReconstruct[i], 0.5);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(matrixBCopy[i], b[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="col">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 4)]
[TestCase(5, 8)]
[TestCase(10, 3)]
[TestCase(50, 10)]
[TestCase(100, 100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int col)
{
var matrixA = new UserDefinedMatrix(Matrix<float>.Build.RandomPositiveDefinite(row, 1).ToArray());
var matrixACopy = matrixA.Clone();
var chol = matrixA.Cholesky();
var matrixB = new UserDefinedMatrix(Matrix<float>.Build.Random(row, col, 1).ToArray());
var matrixBCopy = matrixB.Clone();
var matrixX = new UserDefinedMatrix(row, col);
chol.Solve(matrixB, matrixX);
Assert.AreEqual(matrixB.RowCount, matrixX.RowCount);
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
}
}
| |
/// OSVR-Unity Connection
///
/// http://sensics.com/osvr
///
/// <copyright>
/// Copyright 2014 Sensics, Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/// </copyright>
using UnityEngine;
using System.Collections;
using System.Text;
//a class for storing information about a device based on it's json descriptor file
using Newtonsoft.Json;
using System.IO;
using System;
public class DeviceDescriptor
{
//filename
private string _fileName = "";
public string FileName
{
get { return _fileName; }
set { _fileName = value; }
}
//hmd
private string _vendor = "";
public string Vendor
{
get { return _vendor; }
set { _vendor = value; }
}
private string _model = "";
public string Model
{
get { return _model; }
set { _model = value; }
}
private string _version;
public string Version
{
get { return _version; }
set { _version = value; }
}
private string _note = "";
public string Note
{
get { return _note; }
set { _note = value; }
}
//field of view
private float _monocularHorizontal = 60f;
public float MonocularHorizontal
{
get { return _monocularHorizontal; }
set { _monocularHorizontal = value; }
}
private float _monocularVertical = 60f;
public float MonocularVertical
{
get { return _monocularVertical; }
set { _monocularVertical = value; }
}
private float _overlapPercent = 100f;
public float OverlapPercent
{
get { return _overlapPercent; }
set { _overlapPercent = value; }
}
private float _pitchTilt = 0;
public float PitchTilt
{
get { return _pitchTilt; }
set { _pitchTilt = value; }
}
//resolutions
private int _width = 1920;
public int Width
{
get { return _width; }
set { _width = value; }
}
private int _height = 1080;
public int Height
{
get { return _height; }
set { _height = value; }
}
private int _videoInputs = 1;
public int VideoInputs
{
get { return _videoInputs; }
set { _videoInputs = value; }
}
private string _displayMode = "horz_side_by_side";
public string DisplayMode
{
get { return _displayMode; }
set { _displayMode = value; }
}
private int _numDisplays = 1;
public int NumDisplays
{
get { return _numDisplays; }
set { _numDisplays = value; }
}
//distortion
private float _k1Red = 0;
public float K1Red
{
get { return _k1Red; }
set { _k1Red = value; }
}
private float _k1Green = 0;
public float K1Green
{
get { return _k1Green; }
set { _k1Green = value; }
}
private float _k1Blue = 0;
public float K1Blue
{
get { return _k1Blue; }
set { _k1Blue = value; }
}
//rendering
private float _leftRoll = 0;
public float LeftRoll
{
get { return _leftRoll; }
set { _leftRoll = value; }
}
private float _rightRoll = 0;
public float RightRoll
{
get { return _rightRoll; }
set { _rightRoll = value; }
}
//eyes
private float _centerProjX = 0.5f;
public float CenterProjX
{
get { return _centerProjX; }
set { _centerProjX = value; }
}
private float _centerProjY = 0.5f;
public float CenterProjY
{
get { return _centerProjY; }
set { _centerProjY = value; }
}
private int _rotate180 = 0;
public int Rotate180
{
get { return _rotate180; }
set { _rotate180 = value; }
}
//constructors
public DeviceDescriptor() { }
public DeviceDescriptor(string fileName, string vendor, string model, string version, int numDisplays, string note, float monocularHorizontal,
float monocularVertical, float overlapPercent, float pitchTilt, int width, int height, int videoInputs, string displayMode, float k1Red,
float k1Green, float k1Blue, float leftRoll, float rightRoll, float centerProjX, float centerProjY, int rotate180)
{
this._fileName = fileName;
this._vendor = vendor;
this._model = model;
this._version = version;
this._numDisplays = numDisplays;
this._note = note;
this._monocularHorizontal = monocularHorizontal;
this._monocularVertical = monocularVertical;
this._overlapPercent = overlapPercent;
this._pitchTilt = pitchTilt;
this._width = width;
this._height = height;
this._videoInputs = videoInputs;
this._displayMode = displayMode;
this._k1Red = k1Red;
this._k1Green = k1Green;
this._k1Blue = k1Blue;
this._leftRoll = leftRoll;
this._rightRoll = rightRoll;
this._centerProjX = centerProjX;
this._centerProjY = centerProjY;
this._rotate180 = rotate180;
}
public override string ToString()
{
if (FileName.Equals(""))
{
return "No json file has been provided.";
}
//print
StringBuilder jsonPrinter = new StringBuilder(64);
jsonPrinter.AppendLine("Json File Device Description:")
.Append("filename = ").AppendLine(FileName)
.Append("HMD\n")
.Append("vendor = ").AppendLine(Vendor)
.Append("model = ").AppendLine(Model)
.Append("version = ").AppendLine(Version)
.Append("num_displays = ").AppendLine(NumDisplays.ToString())
.Append("notes = ").AppendLine(Note)
.Append("\nFIELD OF VIEW\n")
.Append("monocular_horizontal = ").AppendLine(MonocularHorizontal.ToString())
.Append("monocular_vertical = ").AppendLine(MonocularVertical.ToString())
.Append("overlap_percent = ").AppendLine(OverlapPercent.ToString())
.Append("pitch_tilt = ").AppendLine(PitchTilt.ToString())
.Append("\nRESOLUTION\n")
.Append("width = ").AppendLine(Width.ToString())
.Append("height = ").AppendLine(Height.ToString())
.Append("video_inputs = ").AppendLine(VideoInputs.ToString())
.Append("display_mode = ").AppendLine(DisplayMode)
.Append("\nDISTORTION\n")
.Append("k1_red = ").AppendLine(K1Red.ToString())
.Append("k1_green = ").AppendLine(K1Green.ToString())
.Append("k1_blue = ").AppendLine(K1Blue.ToString())
.Append("\nRENDERING\n")
.Append("left_roll = ").AppendLine(LeftRoll.ToString())
.Append("right_roll = ").AppendLine(RightRoll.ToString())
.Append("\nEYES\n")
.Append("center_proj_x = ").AppendLine(CenterProjX.ToString())
.Append("center_proj_y = ").AppendLine(CenterProjY.ToString())
.Append("rotate_180 = ").AppendLine(Rotate180.ToString());
return jsonPrinter.ToString();
}
/// <summary>
/// This function will parse the device parameters from a device descriptor json file using Newstonsoft
///
/// Returns a DeviceDescriptor object containing stored json values.
/// </summary>
public static DeviceDescriptor Parse(string deviceDescriptorJson)
{
if (deviceDescriptorJson == null)
{
throw new ArgumentNullException("deviceDescriptorJson");
}
//create a device descriptor object for storing the parsed json in an object
DeviceDescriptor deviceDescriptor;
JsonTextReader reader;
reader = new JsonTextReader(new StringReader(deviceDescriptorJson));
if (reader != null)
{
deviceDescriptor = new DeviceDescriptor();
}
else
{
Debug.LogError("No Device Descriptor detected.");
return null;
}
//parsey
while (reader.Read())
{
if (reader.Value != null && reader.ValueType == typeof(String))
{
string parsedJson = reader.Value.ToString().ToLower();
switch (parsedJson)
{
case "vendor":
deviceDescriptor.Vendor = reader.ReadAsString();
break;
case "model":
deviceDescriptor.Model = reader.ReadAsString();
break;
case "version":
deviceDescriptor.Version = reader.ReadAsString();
break;
case "num_displays":
deviceDescriptor.NumDisplays = int.Parse(reader.ReadAsString());
break;
case "note":
deviceDescriptor.Note = reader.ReadAsString();
break;
case "monocular_horizontal":
deviceDescriptor.MonocularHorizontal = float.Parse(reader.ReadAsString());
break;
case "monocular_vertical":
deviceDescriptor.MonocularVertical = float.Parse(reader.ReadAsString());
break;
case "overlap_percent":
deviceDescriptor.OverlapPercent = float.Parse(reader.ReadAsString());
break;
case "pitch_tilt":
deviceDescriptor.PitchTilt = float.Parse(reader.ReadAsString());
break;
case "width":
deviceDescriptor.Width = int.Parse(reader.ReadAsString());
break;
case "height":
deviceDescriptor.Height = int.Parse(reader.ReadAsString());
break;
case "video_inputs":
deviceDescriptor.VideoInputs = int.Parse(reader.ReadAsString());
break;
case "display_mode":
deviceDescriptor.DisplayMode = reader.ReadAsString();
break;
case "k1_red":
deviceDescriptor.K1Red = float.Parse(reader.ReadAsString());
break;
case "k1_green":
deviceDescriptor.K1Green = float.Parse(reader.ReadAsString());
break;
case "k1_blue":
deviceDescriptor.K1Blue = float.Parse(reader.ReadAsString());
break;
case "right_roll":
deviceDescriptor.RightRoll = float.Parse(reader.ReadAsString());
break;
case "left_roll":
deviceDescriptor.LeftRoll = float.Parse(reader.ReadAsString());
break;
case "center_proj_x":
deviceDescriptor.CenterProjX = float.Parse(reader.ReadAsString());
break;
case "center_proj_y":
deviceDescriptor.CenterProjY = float.Parse(reader.ReadAsString());
break;
case "rotate_180":
deviceDescriptor.Rotate180 = int.Parse(reader.ReadAsString());
break;
}
}
}
return deviceDescriptor;
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
namespace Hydra.Framework.Threading
{
/// <summary>
/// Attempts to provide a method of running asynchronous methods (the BeginXXX/EndXXX style)
/// in a linear manner avoiding all the propogation of those methods up the call stack
/// </summary>
public class AsyncExecutor
: IAsyncExecutor
{
#region Member Variables
/// <summary>
/// Mutex
/// </summary>
private readonly object mutexLock = new object();
/// <summary>
/// Queue
/// </summary>
private readonly ReaderWriterLockedObject<Queue<IAsyncResult>> queue;
/// <summary>
/// Syncronised Context
/// </summary>
private readonly SynchronizationContext syncContext;
/// <summary>
/// Wait Counter
/// </summary>
private readonly ReaderWriterLockedObject<int> waitCount;
/// <summary>
/// Asynchronous Result
/// </summary>
private AsyncResult asyncResult;
/// <summary>
/// Is Cancelled
/// </summary>
private volatile bool isCancelled;
/// <summary>
/// Enumerator
/// </summary>
private IEnumerator<int> enumerator;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="AsyncExecutor"/> class.
/// </summary>
public AsyncExecutor()
{
queue = new ReaderWriterLockedObject<Queue<IAsyncResult>>(new Queue<IAsyncResult>());
waitCount = new ReaderWriterLockedObject<int>(0);
syncContext = SynchronizationContext.Current;
}
#endregion
#region Public Methods
/// <summary>
/// Cancel the execution of an asynchronous method
/// </summary>
public void Cancel()
{
isCancelled = true;
}
/// <summary>
/// Executes a method containing yields, but waits for said method to complete
/// </summary>
/// <param name="enumerator">The method to execute</param>
public void Execute(IEnumerator<int> enumerator)
{
EndExecute(BeginExecute(enumerator, null, null));
}
/// <summary>
/// Asynchronously executes a method containing yields
/// </summary>
/// <param name="enumerator">The method to execute</param>
/// <param name="callback">The asynchronous method to call back</param>
/// <param name="state">A state object passed to the asynchronous callback</param>
/// <returns></returns>
public IAsyncResult BeginExecute(IEnumerator<int> enumerator, AsyncCallback callback, object state)
{
this.enumerator = enumerator;
this.asyncResult = new AsyncResult(callback, state);
ContinueEnumerator(true);
return asyncResult;
}
/// <summary>
/// Completes the execution of an asynchronous methods
/// </summary>
/// <param name="asyncResult"></param>
public void EndExecute(IAsyncResult asyncResult)
{
((Hydra.Framework.Threading.AsyncResult)asyncResult).EndInvoke();
asyncResult = null;
}
/// <summary>
/// Returns a callback for the BeginXXX method being yielded
/// </summary>
/// <returns></returns>
public AsyncCallback End()
{
return EnqueueResultToInbox;
}
/// <summary>
/// Returns the next async result in the queue of completed asynchronous methods
/// </summary>
/// <returns></returns>
public IAsyncResult Result()
{
return queue.WriteLock(x => x.Dequeue());
}
#endregion
#region Private Methods
/// <summary>
/// Enqueues the result to inbox.
/// </summary>
/// <param name="asyncResult">The async result.</param>
private void EnqueueResultToInbox(IAsyncResult asyncResult)
{
queue.WriteLock(x => x.Enqueue(asyncResult));
if (queue.ReadLock(x => x.Count) == waitCount.ReadLock(x => x))
ContinueEnumerator(false);
}
/// <summary>
/// Continues the enumerator.
/// </summary>
/// <param name="outsideOfSyncContext">if set to <c>true</c> [outside of sync context].</param>
private void ContinueEnumerator(bool outsideOfSyncContext)
{
if (syncContext != null &&
outsideOfSyncContext)
{
syncContext.Post(SyncContextContinueEnumerator, this);
return;
}
Exception caughtException = null;
lock (mutexLock)
{
bool stillGoing = false;
try
{
while ((stillGoing = enumerator.MoveNext()))
{
if (HasBeenCancelled())
continue;
int expectedResultCount = enumerator.Current;
if (expectedResultCount == 0)
{
ThreadPool.QueueUserWorkItem(ThreadPoolContinueEnumerator, this);
return;
}
waitCount.WriteLock(x => expectedResultCount);
return;
}
}
catch (Exception ex)
{
caughtException = ex;
throw;
}
finally
{
if (!stillGoing)
{
enumerator.Dispose();
if (caughtException != null)
{
asyncResult.SetAsCompleted(caughtException);
}
else
{
asyncResult.SetAsCompleted();
}
}
}
}
}
/// <summary>
/// Determines whether [has been cancelled].
/// </summary>
/// <returns>
/// <c>true</c> if [has been cancelled]; otherwise, <c>false</c>.
/// </returns>
private bool HasBeenCancelled()
{
return isCancelled;
}
#endregion
#region Static Methods
/// <summary>
/// Runs the specified action.
/// </summary>
/// <param name="action">The action.</param>
public static void Run(Func<IAsyncExecutor, IEnumerator<int>> action)
{
AsyncExecutor executor = new AsyncExecutor();
executor.Execute(action(executor));
}
/// <summary>
/// Runs the async.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="complete">The complete.</param>
/// <returns></returns>
public static IAsyncResult RunAsync(Func<IAsyncExecutor, IEnumerator<int>> action, Action complete)
{
AsyncExecutor executor = new AsyncExecutor();
AsyncCallback callback = x =>
{
executor.EndExecute(x);
complete();
};
return executor.BeginExecute(action(executor), callback, null);
}
/// <summary>
/// Runs the async.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="action">The action.</param>
/// <param name="state">The state.</param>
/// <param name="complete">The complete.</param>
/// <returns></returns>
public static IAsyncResult RunAsync<T>(Func<IAsyncExecutor, IEnumerator<int>> action, T state, Action<T> complete)
{
AsyncExecutor executor = new AsyncExecutor();
AsyncCallback callback = x =>
{
executor.EndExecute(x);
complete(state);
};
return executor.BeginExecute(action(executor), callback, state);
}
/// <summary>
/// Syncs the context continue enumerator.
/// </summary>
/// <param name="state">The state.</param>
private static void SyncContextContinueEnumerator(object state)
{
((AsyncExecutor)state).ContinueEnumerator(false);
}
/// <summary>
/// Threads the pool continue enumerator.
/// </summary>
/// <param name="state">The state.</param>
private static void ThreadPoolContinueEnumerator(object state)
{
((AsyncExecutor)state).ContinueEnumerator(true);
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using HappyMapper.AutoMapper.ConfigurationAPI.Configuration;
using HappyMapper.AutoMapper.ConfigurationAPI.Mappers;
using HappyMapper.AutoMapper.ConfigurationAPI.QueryableExtensions;
using HappyMapper.AutoMapper.ConfigurationAPI.QueryableExtensions.Impl;
namespace HappyMapper.AutoMapper.ConfigurationAPI
{
using UntypedMapperFunc = System.Func<object, object, ResolutionContext, object>;
public class MapperConfiguration : IConfigurationProvider
{
private readonly IEnumerable<IObjectMapper> _mappers;
public TypeMapRegistry TypeMapRegistry { get; } = new TypeMapRegistry();
private readonly ConcurrentDictionary<TypePair, TypeMap> _typeMapPlanCache = new ConcurrentDictionary<TypePair, TypeMap>();
private readonly ConcurrentDictionary<MapRequest, MapperFuncs> _mapPlanCache = new ConcurrentDictionary<MapRequest, MapperFuncs>();
private readonly ConfigurationValidator _validator;
private readonly Func<TypePair, TypeMap> _getTypeMap;
private readonly Func<MapRequest, MapperFuncs> _createMapperFuncs;
public MapperConfiguration(MapperConfigurationExpression configurationExpression)
: this(configurationExpression, MapperRegistry.Mappers)
{
}
public MapperConfiguration(MapperConfigurationExpression configurationExpression, IEnumerable<IObjectMapper> mappers)
{
_mappers = mappers;
_getTypeMap = GetTypeMap;
_createMapperFuncs = CreateMapperFuncs;
_validator = new ConfigurationValidator(this);
ExpressionBuilder = new ExpressionBuilder(this);
Configuration = configurationExpression;
Seal(Configuration);
}
public MapperConfiguration(Action<IMapperConfigurationExpression> configure) : this(configure, MapperRegistry.Mappers)
{
}
public MapperConfiguration(Action<IMapperConfigurationExpression> configure, IEnumerable<IObjectMapper> mappers)
: this(Build(configure), mappers)
{
}
public IExpressionBuilder ExpressionBuilder { get; }
public Func<Type, object> ServiceCtor { get; private set; }
public bool AllowNullDestinationValues { get; private set; }
public bool AllowNullCollections { get; private set; }
public IConfiguration Configuration { get; }
public Func<TSource, TDestination, ResolutionContext, TDestination> GetMapperFunc<TSource, TDestination>(TypePair types)
{
var key = new TypePair(typeof(TSource), typeof(TDestination));
var mapRequest = new MapRequest(key, types);
return (Func<TSource, TDestination, ResolutionContext, TDestination>)GetMapperFunc(mapRequest);
}
public Delegate GetMapperFunc(MapRequest mapRequest)
{
return _mapPlanCache.GetOrAdd(mapRequest, _createMapperFuncs).Typed;
}
public UntypedMapperFunc GetUntypedMapperFunc(MapRequest mapRequest)
{
return _mapPlanCache.GetOrAdd(mapRequest, _createMapperFuncs).Untyped;
}
private MapperFuncs CreateMapperFuncs(MapRequest mapRequest)
{
var typeMap = ResolveTypeMap(mapRequest.RuntimeTypes);
if (typeMap != null)
{
return new MapperFuncs(mapRequest, typeMap);
}
var mapperToUse = _mappers.FirstOrDefault(om => om.IsMatch(mapRequest.RuntimeTypes));
return new MapperFuncs(mapRequest, mapperToUse, this);
}
public TypeMap[] GetAllTypeMaps() => TypeMapRegistry.TypeMaps.ToArray();
public TypeMap FindTypeMapFor(Type sourceType, Type destinationType) => FindTypeMapFor(new TypePair(sourceType, destinationType));
public TypeMap FindTypeMapFor<TSource, TDestination>() => FindTypeMapFor(new TypePair(typeof(TSource), typeof(TDestination)));
public TypeMap FindTypeMapFor(TypePair typePair) => TypeMapRegistry.GetTypeMap(typePair);
public TypeMap ResolveTypeMap(Type sourceType, Type destinationType)
{
var typePair = new TypePair(sourceType, destinationType);
return ResolveTypeMap(typePair);
}
public TypeMap ResolveTypeMap(TypePair typePair)
{
var typeMap = _typeMapPlanCache.GetOrAdd(typePair, _getTypeMap);
if(Configuration.CreateMissingTypeMaps && typeMap != null && typeMap.MapExpression == null)
{
lock(typeMap)
{
typeMap.Seal(TypeMapRegistry, this);
}
}
return typeMap;
}
private TypeMap GetTypeMap(TypePair initialTypes)
{
TypeMap typeMap;
foreach(var types in initialTypes.GetRelatedTypePairs())
{
if(_typeMapPlanCache.TryGetValue(types, out typeMap))
{
return typeMap;
}
typeMap = FindTypeMapFor(types);
if(typeMap != null)
{
return typeMap;
}
typeMap = FindClosedGenericTypeMapFor(types, initialTypes);
if(typeMap != null)
{
return typeMap;
}
if(!CoveredByObjectMap(initialTypes))
{
typeMap = FindConventionTypeMapFor(types);
if(typeMap != null)
{
return typeMap;
}
}
}
return null;
}
public void AssertConfigurationIsValid(TypeMap typeMap)
{
_validator.AssertConfigurationIsValid(Enumerable.Repeat(typeMap, 1));
}
public void AssertConfigurationIsValid(string profileName)
{
_validator.AssertConfigurationIsValid(TypeMapRegistry.TypeMaps.Where(typeMap => typeMap.Profile.ProfileName == profileName));
}
public void AssertConfigurationIsValid<TProfile>()
where TProfile : Profile, new()
{
AssertConfigurationIsValid(new TProfile().ProfileName);
}
public void AssertConfigurationIsValid()
{
_validator.AssertConfigurationIsValid(TypeMapRegistry.TypeMaps.Where(tm => !tm.SourceType.IsGenericTypeDefinition() && !tm.DestinationType.IsGenericTypeDefinition()));
}
public IMapper CreateMapper() => new Mapper(this);
public IMapper CreateMapper(Func<Type, object> serviceCtor) => new Mapper(this, serviceCtor);
public IEnumerable<IObjectMapper> GetMappers() => _mappers;
private static MapperConfigurationExpression Build(Action<IMapperConfigurationExpression> configure)
{
var expr = new MapperConfigurationExpression();
configure(expr);
return expr;
}
private void Seal(IConfiguration configuration)
{
ServiceCtor = configuration.ServiceCtor;
AllowNullDestinationValues = configuration.AllowNullDestinationValues;
AllowNullCollections = configuration.AllowNullCollections;
var derivedMaps = new List<Tuple<TypePair, TypeMap>>();
var redirectedTypes = new List<Tuple<TypePair, TypePair>>();
foreach (var profile in configuration.Profiles.Cast<IProfileConfiguration>())
{
profile.Register(TypeMapRegistry);
}
foreach (var action in configuration.AllTypeMapActions)
{
foreach (var typeMap in TypeMapRegistry.TypeMaps)
{
var expression = new MappingExpression(typeMap.TypePair, typeMap.ConfiguredMemberList);
action(typeMap, expression);
expression.Configure(typeMap.Profile, typeMap);
}
}
foreach (var action in configuration.AllPropertyMapActions)
{
foreach (var typeMap in TypeMapRegistry.TypeMaps)
{
foreach (var propertyMap in typeMap.GetPropertyMaps())
{
var memberExpression = new MappingExpression.MemberConfigurationExpression(propertyMap.DestMember, typeMap.SourceType);
action(propertyMap, memberExpression);
memberExpression.Configure(typeMap);
}
}
}
foreach (var profile in configuration.Profiles.Cast<IProfileConfiguration>())
{
profile.Configure(TypeMapRegistry);
}
foreach (var typeMap in TypeMapRegistry.TypeMaps)
{
_typeMapPlanCache[typeMap.TypePair] = typeMap;
if (typeMap.DestinationTypeOverride != null)
{
redirectedTypes.Add(Tuple.Create(typeMap.TypePair, new TypePair(typeMap.SourceType, typeMap.DestinationTypeOverride)));
}
if (typeMap.SourceType.IsNullableType())
{
var nonNullableTypes = new TypePair(Nullable.GetUnderlyingType(typeMap.SourceType), typeMap.DestinationType);
redirectedTypes.Add(Tuple.Create(nonNullableTypes, typeMap.TypePair));
}
derivedMaps.AddRange(GetDerivedTypeMaps(typeMap).Select(derivedMap => Tuple.Create(new TypePair(derivedMap.SourceType, typeMap.DestinationType), derivedMap)));
}
foreach (var redirectedType in redirectedTypes)
{
var derivedMap = FindTypeMapFor(redirectedType.Item2);
if (derivedMap != null)
{
_typeMapPlanCache[redirectedType.Item1] = derivedMap;
}
}
foreach (var derivedMap in derivedMaps.Where(derivedMap => !_typeMapPlanCache.ContainsKey(derivedMap.Item1)))
{
_typeMapPlanCache[derivedMap.Item1] = derivedMap.Item2;
}
foreach (var typeMap in TypeMapRegistry.TypeMaps)
{
typeMap.Seal(TypeMapRegistry, this);
}
}
private IEnumerable<TypeMap> GetDerivedTypeMaps(TypeMap typeMap)
{
foreach (var derivedTypes in typeMap.IncludedDerivedTypes)
{
var derivedMap = FindTypeMapFor(derivedTypes);
if (derivedMap == null)
{
throw QueryMapperHelper.MissingMapException(derivedTypes.SourceType, derivedTypes.DestinationType);
}
yield return derivedMap;
foreach (var derivedTypeMap in GetDerivedTypeMaps(derivedMap))
{
yield return derivedTypeMap;
}
}
}
private bool CoveredByObjectMap(TypePair typePair)
{
return GetMappers().FirstOrDefault(m => m.IsMatch(typePair)) != null;
}
private TypeMap FindConventionTypeMapFor(TypePair typePair)
{
var typeMap = Configuration.Profiles
.Cast<IProfileConfiguration>()
.Select(p => p.ConfigureConventionTypeMap(TypeMapRegistry, typePair))
.FirstOrDefault(t => t != null);
if(!Configuration.CreateMissingTypeMaps)
{
typeMap?.Seal(TypeMapRegistry, this);
}
return typeMap;
}
private TypeMap FindClosedGenericTypeMapFor(TypePair typePair, TypePair requestedTypes)
{
if (typePair.GetOpenGenericTypePair() == null)
return null;
var typeMap = Configuration.Profiles
.Cast<IProfileConfiguration>()
.Select(p => p.ConfigureClosedGenericTypeMap(TypeMapRegistry, typePair, requestedTypes))
.FirstOrDefault(t => t != null);
typeMap?.Seal(TypeMapRegistry, this);
return typeMap;
}
struct MapperFuncs
{
private Lazy<UntypedMapperFunc> _untyped;
public Delegate Typed { get; }
public UntypedMapperFunc Untyped => _untyped.Value;
public MapperFuncs(MapRequest mapRequest, TypeMap typeMap) : this(mapRequest, GenerateTypeMapExpression(mapRequest, typeMap))
{
}
public MapperFuncs(MapRequest mapRequest, IObjectMapper mapperToUse, MapperConfiguration mapperConfiguration) : this(mapRequest, GenerateObjectMapperExpression(mapRequest, mapperToUse, mapperConfiguration))
{
}
public MapperFuncs(MapRequest mapRequest, LambdaExpression typedExpression)
{
Typed = typedExpression.Compile();
_untyped = new Lazy<UntypedMapperFunc>(() => Wrap(mapRequest, typedExpression).Compile());
}
private static Expression<UntypedMapperFunc> Wrap(MapRequest mapRequest, LambdaExpression typedExpression)
{
var sourceParameter = Expression.Parameter(typeof(object), "source");
var destinationParameter = Expression.Parameter(typeof(object), "destination");
var contextParameter = Expression.Parameter(typeof(ResolutionContext), "context");
var requestedSourceType = mapRequest.RequestedTypes.SourceType;
var requestedDestinationType = mapRequest.RequestedTypes.DestinationType;
var destination = requestedDestinationType.IsValueType() ? Expression.Coalesce(destinationParameter, Expression.New(requestedDestinationType)) : (Expression)destinationParameter;
// Invoking a delegate here
return Expression.Lambda<UntypedMapperFunc>(
ExpressionExtensions.ToType(
Expression.Invoke(typedExpression, ExpressionExtensions.ToType(sourceParameter, requestedSourceType), ExpressionExtensions.ToType(destination, requestedDestinationType), contextParameter)
, typeof(object)),
sourceParameter, destinationParameter, contextParameter);
}
private static LambdaExpression GenerateTypeMapExpression(MapRequest mapRequest, TypeMap typeMap)
{
var mapExpression = typeMap.MapExpression;
var typeMapSourceParameter = mapExpression.Parameters[0];
var typeMapDestinationParameter = mapExpression.Parameters[1];
var requestedSourceType = mapRequest.RequestedTypes.SourceType;
var requestedDestinationType = mapRequest.RequestedTypes.DestinationType;
if (typeMapSourceParameter.Type != requestedSourceType || typeMapDestinationParameter.Type != requestedDestinationType)
{
var requestedSourceParameter = Expression.Parameter(requestedSourceType, "source");
var requestedDestinationParameter = Expression.Parameter(requestedDestinationType, "typeMapDestination");
var contextParameter = Expression.Parameter(typeof(ResolutionContext), "context");
mapExpression = Expression.Lambda(ExpressionExtensions.ToType(Expression.Invoke(typeMap.MapExpression,
ExpressionExtensions.ToType(requestedSourceParameter, typeMapSourceParameter.Type),
ExpressionExtensions.ToType(requestedDestinationParameter, typeMapDestinationParameter.Type),
contextParameter
), mapRequest.RuntimeTypes.DestinationType),
requestedSourceParameter, requestedDestinationParameter, contextParameter);
}
return mapExpression;
}
private static readonly ConstructorInfo ExceptionConstructor = typeof(AutoMapperMappingException).GetConstructors().Single(c => c.GetParameters().Length == 3);
private static LambdaExpression GenerateObjectMapperExpression(MapRequest mapRequest, IObjectMapper mapperToUse, MapperConfiguration mapperConfiguration)
{
var destinationType = mapRequest.RequestedTypes.DestinationType;
var source = Expression.Parameter(mapRequest.RequestedTypes.SourceType, "source");
var destination = Expression.Parameter(destinationType, "mapperDestination");
var context = Expression.Parameter(typeof(ResolutionContext), "context");
LambdaExpression fullExpression;
if (mapperToUse == null)
{
var message = Expression.Constant("Missing type map configuration or unsupported mapping.");
fullExpression = Expression.Lambda(Expression.Block(Expression.Throw(Expression.New(ExceptionConstructor, message, Expression.Constant(null, typeof(Exception)), Expression.Constant(mapRequest.RequestedTypes))), Expression.Default(destinationType)), source, destination, context);
}
else
{
var map = mapperToUse.MapExpression(mapperConfiguration.TypeMapRegistry, mapperConfiguration, null, ExpressionExtensions.ToType(source, mapRequest.RuntimeTypes.SourceType), destination, context);
var mapToDestination = Expression.Lambda(ExpressionExtensions.ToType(map, destinationType), source, destination, context);
fullExpression = TryCatch(mapToDestination, source, destination, context, mapRequest.RequestedTypes);
}
return fullExpression;
}
private static LambdaExpression TryCatch(LambdaExpression mapExpression, ParameterExpression source, ParameterExpression destination, ParameterExpression context, TypePair types)
{
var exception = Expression.Parameter(typeof(Exception), "ex");
return Expression.Lambda(Expression.TryCatch(mapExpression.Body,
Expression.MakeCatchBlock(typeof(Exception), exception, Expression.Block(
Expression.Throw(Expression.New(ExceptionConstructor, Expression.Constant("Error mapping types."), exception, Expression.Constant(types))),
Expression.Default(destination.Type)), null)),
source, destination, context);
}
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_15_5_4_13 : EcmaTest
{
[Fact]
[Trait("Category", "15.5.4.13")]
public void TheStringPrototypeSliceLengthPropertyHasTheAttributeReadonly()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A10.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void TheLengthPropertyOfTheSliceMethodIs2()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A11.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T1.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd2()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T10.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd3()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T11.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd4()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T12.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd5()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T13.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd6()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T14.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd7()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T15.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd8()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T2.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd9()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T4.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd10()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T5.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd11()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T6.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd12()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T7.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd13()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T8.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEnd14()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A1_T9.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndReturnsAStringValueNotObject()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A2_T1.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndReturnsAStringValueNotObject2()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A2_T2.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndReturnsAStringValueNotObject3()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A2_T3.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndReturnsAStringValueNotObject4()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A2_T4.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndReturnsAStringValueNotObject5()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A2_T5.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndReturnsAStringValueNotObject6()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A2_T6.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndReturnsAStringValueNotObject7()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A2_T7.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndReturnsAStringValueNotObject8()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A2_T8.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndReturnsAStringValueNotObject9()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A2_T9.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndCanBeAppliedToObjectInstances()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A3_T1.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndCanBeAppliedToObjectInstances2()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A3_T2.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndCanBeAppliedToObjectInstances3()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A3_T3.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceStartEndCanBeAppliedToObjectInstances4()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A3_T4.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceHasNotPrototypeProperty()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A6.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void StringPrototypeSliceCanTBeUsedAsConstructor()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A7.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void TheStringPrototypeSliceLengthPropertyHasTheAttributeDontenum()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A8.js", false);
}
[Fact]
[Trait("Category", "15.5.4.13")]
public void TheStringPrototypeSliceLengthPropertyHasTheAttributeDontdelete()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.13/S15.5.4.13_A9.js", false);
}
}
}
| |
using System;
namespace AutoMapper
{
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using ObjectMappingOperationOptions = MappingOperationOptions<object, object>;
using QueryableExtensions;
public class Mapper : IRuntimeMapper
{
internal const string NoContextMapperOptions = "Set options in the outer Map call instead.";
public Mapper(IConfigurationProvider configurationProvider)
: this(configurationProvider, configurationProvider.ServiceCtor)
{
}
public Mapper(IConfigurationProvider configurationProvider, Func<Type, object> serviceCtor)
{
ConfigurationProvider = configurationProvider ?? throw new ArgumentNullException(nameof(configurationProvider));
ServiceCtor = serviceCtor ?? throw new ArgumentNullException(nameof(serviceCtor));
DefaultContext = new ResolutionContext(new ObjectMappingOperationOptions(serviceCtor), this);
}
public ResolutionContext DefaultContext { get; }
public Func<Type, object> ServiceCtor { get; }
public IConfigurationProvider ConfigurationProvider { get; }
public TDestination Map<TDestination>(object source)
{
var types = new TypePair(source?.GetType() ?? typeof(object), typeof(TDestination));
var func = ConfigurationProvider.GetUntypedMapperFunc(new MapRequest(types, types));
return (TDestination) func(source, null, DefaultContext);
}
public TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
{
var sourceType = source?.GetType() ?? typeof(object);
var destinationType = typeof(TDestination);
var mappedObject = (TDestination)((IMapper)this).Map(source, sourceType, destinationType, opts);
return mappedObject;
}
public TDestination Map<TSource, TDestination>(TSource source)
{
var types = TypePair.Create(source, typeof(TSource), typeof (TDestination));
var func = ConfigurationProvider.GetMapperFunc<TSource, TDestination>(types);
var destination = default(TDestination);
return func(source, destination, DefaultContext);
}
public TDestination Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
var types = TypePair.Create(source, typeof(TSource), typeof(TDestination));
var key = new TypePair(typeof(TSource), typeof(TDestination));
var typedOptions = new MappingOperationOptions<TSource, TDestination>(ServiceCtor);
opts(typedOptions);
var mapRequest = new MapRequest(key, types);
var func = ConfigurationProvider.GetMapperFunc<TSource, TDestination>(mapRequest);
var destination = default(TDestination);
typedOptions.BeforeMapAction(source, destination);
var context = new ResolutionContext(typedOptions, this);
destination = func(source, destination, context);
typedOptions.AfterMapAction(source, destination);
return destination;
}
public TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
{
var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination));
var func = ConfigurationProvider.GetMapperFunc<TSource, TDestination>(types);
return func(source, destination, DefaultContext);
}
public TDestination Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination));
var key = new TypePair(typeof(TSource), typeof(TDestination));
var typedOptions = new MappingOperationOptions<TSource, TDestination>(ServiceCtor);
opts(typedOptions);
var mapRequest = new MapRequest(key, types);
var func = ConfigurationProvider.GetMapperFunc<TSource, TDestination>(mapRequest);
typedOptions.BeforeMapAction(source, destination);
var context = new ResolutionContext(typedOptions, this);
destination = func(source, destination, context);
typedOptions.AfterMapAction(source, destination);
return destination;
}
public object Map(object source, Type sourceType, Type destinationType)
{
var types = TypePair.Create(source, sourceType, destinationType);
var func = ConfigurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
return func(source, null, DefaultContext);
}
public object Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
{
var types = TypePair.Create(source, sourceType, destinationType);
var options = new ObjectMappingOperationOptions(ServiceCtor);
opts(options);
var func = ConfigurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
options.BeforeMapAction(source, null);
var context = new ResolutionContext(options, this);
var destination = func(source, null, context);
options.AfterMapAction(source, destination);
return destination;
}
public object Map(object source, object destination, Type sourceType, Type destinationType)
{
var types = TypePair.Create(source, destination, sourceType, destinationType);
var func = ConfigurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
return func(source, destination, DefaultContext);
}
public object Map(object source, object destination, Type sourceType, Type destinationType,
Action<IMappingOperationOptions> opts)
{
var types = TypePair.Create(source, destination, sourceType, destinationType);
var options = new ObjectMappingOperationOptions(ServiceCtor);
opts(options);
var func = ConfigurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
options.BeforeMapAction(source, destination);
var context = new ResolutionContext(options, this);
destination = func(source, destination, context);
options.AfterMapAction(source, destination);
return destination;
}
public object Map(object source, object destination, Type sourceType, Type destinationType,
ResolutionContext context, IMemberMap memberMap)
{
var types = TypePair.Create(source, destination, sourceType, destinationType);
var func = ConfigurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types, memberMap));
return func(source, destination, context);
}
public TDestination Map<TSource, TDestination>(TSource source, TDestination destination,
ResolutionContext context, IMemberMap memberMap)
{
var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination));
var func = ConfigurationProvider.GetMapperFunc<TSource, TDestination>(types, memberMap);
return func(source, destination, context);
}
public IQueryable<TDestination> ProjectTo<TDestination>(IQueryable source, object parameters, params Expression<Func<TDestination, object>>[] membersToExpand)
=> source.ProjectTo(ConfigurationProvider, parameters, membersToExpand);
public IQueryable<TDestination> ProjectTo<TDestination>(IQueryable source, IDictionary<string, object> parameters, params string[] membersToExpand)
=> source.ProjectTo<TDestination>(ConfigurationProvider, parameters, membersToExpand);
public IQueryable ProjectTo(IQueryable source, Type destinationType, IDictionary<string, object> parameters, params string[] membersToExpand)
=> source.ProjectTo(destinationType, ConfigurationProvider, parameters, membersToExpand);
}
}
| |
namespace Sitecore.FakeDb
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Xml;
using Sitecore.Common;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.FakeDb.Configuration;
using Sitecore.FakeDb.Data.Engines;
using Sitecore.FakeDb.Pipelines;
using Sitecore.FakeDb.Pipelines.InitFakeDb;
using Sitecore.FakeDb.Pipelines.ReleaseFakeDb;
using Sitecore.Globalization;
using Sitecore.Pipelines;
using Version = Sitecore.Data.Version;
/// <summary>
/// Creates Sitecore items in memory.
/// </summary>
public class Db : IDisposable, IEnumerable
{
private static readonly object Lock = new object();
private readonly Database database;
private readonly DataStorage dataStorage;
private readonly DataStorageSwitcher dataStorageSwitcher;
private readonly DatabaseSwitcher databaseSwitcher;
private readonly Stack<Switcher<DbLanguages>> databaseLanguages;
private DbConfiguration configuration;
private PipelineWatcher pipelineWatcher;
private XmlDocument config;
private bool disposed;
/// <summary>
/// Initializes a new instance of the <see cref="Db"/> class with the "master" database.
/// </summary>
public Db()
: this("master")
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Db"/> class with the specified database.
/// </summary>
/// <param name="databaseName">The database name.</param>
public Db(string databaseName)
{
Assert.ArgumentNotNullOrEmpty(databaseName, "databaseName");
this.database = Database.GetDatabase(databaseName);
this.dataStorage = new DataStorage(this.database);
this.dataStorageSwitcher = new DataStorageSwitcher(this.dataStorage);
this.databaseSwitcher = new DatabaseSwitcher(this.database);
this.databaseLanguages = new Stack<Switcher<DbLanguages>>();
this.databaseLanguages.Push(
new Switcher<DbLanguages>(
new DbLanguages(Language.Parse("en"))));
var args = new InitDbArgs(this.database, this.dataStorage);
CorePipeline.Run("initFakeDb", args);
}
internal Db(PipelineWatcher pipelineWatcher)
: this()
{
this.pipelineWatcher = pipelineWatcher;
}
public Database Database
{
get { return this.database; }
}
public DbConfiguration Configuration
{
get
{
if (this.configuration != null)
{
return this.configuration;
}
this.config = this.GetConfiguration();
this.configuration = new DbConfiguration(this.config);
return this.configuration;
}
}
public PipelineWatcher PipelineWatcher
{
get
{
if (this.pipelineWatcher != null)
{
return this.pipelineWatcher;
}
this.config = this.GetConfiguration();
this.pipelineWatcher = new PipelineWatcher(this.config);
return this.pipelineWatcher;
}
}
protected internal DataStorage DataStorage
{
get { return this.dataStorage; }
}
public IEnumerator GetEnumerator()
{
return this.DataStorage.GetFakeItems().GetEnumerator();
}
/// <summary>
/// Adds a <see cref="DbItem" /> to the current database.
/// </summary>
/// <param name="item">The item to add.</param>
public void Add(DbItem item)
{
Assert.ArgumentNotNull(item, "item");
this.DataStorage.AddFakeItem(item);
}
/// <summary>
/// Gets an <see cref="Item"/> by id.
/// </summary>
/// <param name="id">The item id.</param>
/// <returns>The item.</returns>
public Item GetItem(ID id)
{
return this.Database.GetItem(id);
}
/// <summary>
/// Gets an <see cref="Item"/> by id and language.
/// </summary>
/// <param name="id">The item id.</param>
/// <param name="language">The item language.</param>
/// <returns>The item.</returns>
public Item GetItem(ID id, string language)
{
Assert.ArgumentNotNullOrEmpty(language, "language");
return this.Database.GetItem(id, Language.Parse(language));
}
/// <summary>
/// Gets an <see cref="Item"/> by id, language and version number.
/// </summary>
/// <param name="id">The item id.</param>
/// <param name="language">The item language.</param>
/// <param name="version">The item version.</param>
/// <returns>The item.</returns>
public Item GetItem(ID id, string language, int version)
{
Assert.ArgumentNotNullOrEmpty(language, "language");
return this.Database.GetItem(id, Language.Parse(language), Version.Parse(version));
}
/// <summary>
/// Gets an <see cref="Item" /> by path.
/// </summary>
/// <param name="path">The item path.</param>
/// <returns>The item.</returns>
public Item GetItem(string path)
{
Assert.ArgumentNotNullOrEmpty(path, "path");
return this.Database.GetItem(path);
}
/// <summary>
/// Gets an <see cref="Item"/> by path and language.
/// </summary>
/// <param name="path">The item path.</param>
/// <param name="language">The item language.</param>
/// <returns>The item.</returns>
public Item GetItem(string path, string language)
{
Assert.ArgumentNotNullOrEmpty(path, "path");
Assert.ArgumentNotNull(language, "language");
return this.Database.GetItem(path, Language.Parse(language));
}
/// <summary>
/// Gets an <see cref="Item"/> by path, language and version number.
/// </summary>
/// <param name="path">The item path.</param>
/// <param name="language">The item language.</param>
/// <param name="version">The item version.</param>
/// <returns>The item.</returns>
public Item GetItem(string path, string language, int version)
{
Assert.ArgumentNotNullOrEmpty(path, "path");
Assert.ArgumentNotNull(language, "language");
return this.Database.GetItem(path, Language.Parse(language), Version.Parse(version));
}
/// <summary>
/// Specifies a list of available <see cref="Database"/> languages for
/// the given <see cref="Db"/> context. If not called, the 'en'
/// language is used.
/// </summary>
/// <param name="languages">The list of languages.</param>
/// <returns>The same <see cref="Db"/> instance.</returns>
public Db WithLanguages(params Language[] languages)
{
this.databaseLanguages.Push(
new Switcher<DbLanguages>(
new DbLanguages(languages)));
return this;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <param name="disposing">True if disposing, otherwise false.</param>
protected virtual void Dispose(bool disposing)
{
if (this.disposed)
{
return;
}
if (!disposing)
{
return;
}
CorePipeline.Run("releaseFakeDb", new ReleaseDbArgs(this));
this.dataStorageSwitcher.Dispose();
this.databaseSwitcher.Dispose();
this.configuration?.Dispose();
foreach (var languageSwitcher in this.databaseLanguages)
{
if (Switcher<DbLanguages>.CurrentValue != null)
{
languageSwitcher.Dispose();
}
}
if (Monitor.IsEntered(Lock))
{
Monitor.Exit(Lock);
}
this.disposed = true;
}
private XmlDocument GetConfiguration()
{
if (this.config != null)
{
return this.config;
}
Monitor.Enter(Lock);
this.config = Factory.GetConfiguration();
return this.config;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Notebooks.V1Beta1.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
using gcnv = Google.Cloud.Notebooks.V1Beta1;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedNotebookServiceClientSnippets
{
/// <summary>Snippet for ListInstances</summary>
public void ListInstancesRequestObject()
{
// Snippet: ListInstances(ListInstancesRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
ListInstancesRequest request = new ListInstancesRequest { Parent = "", };
// Make the request
PagedEnumerable<ListInstancesResponse, Instance> response = notebookServiceClient.ListInstances(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Instance item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListInstancesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Instance item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Instance> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Instance item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListInstancesAsync</summary>
public async Task ListInstancesRequestObjectAsync()
{
// Snippet: ListInstancesAsync(ListInstancesRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
ListInstancesRequest request = new ListInstancesRequest { Parent = "", };
// Make the request
PagedAsyncEnumerable<ListInstancesResponse, Instance> response = notebookServiceClient.ListInstancesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Instance item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListInstancesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Instance item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Instance> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Instance item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetInstance</summary>
public void GetInstanceRequestObject()
{
// Snippet: GetInstance(GetInstanceRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
GetInstanceRequest request = new GetInstanceRequest { Name = "", };
// Make the request
Instance response = notebookServiceClient.GetInstance(request);
// End snippet
}
/// <summary>Snippet for GetInstanceAsync</summary>
public async Task GetInstanceRequestObjectAsync()
{
// Snippet: GetInstanceAsync(GetInstanceRequest, CallSettings)
// Additional: GetInstanceAsync(GetInstanceRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
GetInstanceRequest request = new GetInstanceRequest { Name = "", };
// Make the request
Instance response = await notebookServiceClient.GetInstanceAsync(request);
// End snippet
}
/// <summary>Snippet for CreateInstance</summary>
public void CreateInstanceRequestObject()
{
// Snippet: CreateInstance(CreateInstanceRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
CreateInstanceRequest request = new CreateInstanceRequest
{
Parent = "",
InstanceId = "",
Instance = new Instance(),
};
// Make the request
Operation<Instance, OperationMetadata> response = notebookServiceClient.CreateInstance(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceCreateInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateInstanceAsync</summary>
public async Task CreateInstanceRequestObjectAsync()
{
// Snippet: CreateInstanceAsync(CreateInstanceRequest, CallSettings)
// Additional: CreateInstanceAsync(CreateInstanceRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
CreateInstanceRequest request = new CreateInstanceRequest
{
Parent = "",
InstanceId = "",
Instance = new Instance(),
};
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.CreateInstanceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceCreateInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for RegisterInstance</summary>
public void RegisterInstanceRequestObject()
{
// Snippet: RegisterInstance(RegisterInstanceRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
RegisterInstanceRequest request = new RegisterInstanceRequest
{
Parent = "",
InstanceId = "",
};
// Make the request
Operation<Instance, OperationMetadata> response = notebookServiceClient.RegisterInstance(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceRegisterInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for RegisterInstanceAsync</summary>
public async Task RegisterInstanceRequestObjectAsync()
{
// Snippet: RegisterInstanceAsync(RegisterInstanceRequest, CallSettings)
// Additional: RegisterInstanceAsync(RegisterInstanceRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
RegisterInstanceRequest request = new RegisterInstanceRequest
{
Parent = "",
InstanceId = "",
};
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.RegisterInstanceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceRegisterInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetInstanceAccelerator</summary>
public void SetInstanceAcceleratorRequestObject()
{
// Snippet: SetInstanceAccelerator(SetInstanceAcceleratorRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
SetInstanceAcceleratorRequest request = new SetInstanceAcceleratorRequest
{
Name = "",
Type = Instance.Types.AcceleratorType.Unspecified,
CoreCount = 0L,
};
// Make the request
Operation<Instance, OperationMetadata> response = notebookServiceClient.SetInstanceAccelerator(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceSetInstanceAccelerator(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetInstanceAcceleratorAsync</summary>
public async Task SetInstanceAcceleratorRequestObjectAsync()
{
// Snippet: SetInstanceAcceleratorAsync(SetInstanceAcceleratorRequest, CallSettings)
// Additional: SetInstanceAcceleratorAsync(SetInstanceAcceleratorRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
SetInstanceAcceleratorRequest request = new SetInstanceAcceleratorRequest
{
Name = "",
Type = Instance.Types.AcceleratorType.Unspecified,
CoreCount = 0L,
};
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.SetInstanceAcceleratorAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceSetInstanceAcceleratorAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetInstanceMachineType</summary>
public void SetInstanceMachineTypeRequestObject()
{
// Snippet: SetInstanceMachineType(SetInstanceMachineTypeRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
SetInstanceMachineTypeRequest request = new SetInstanceMachineTypeRequest
{
Name = "",
MachineType = "",
};
// Make the request
Operation<Instance, OperationMetadata> response = notebookServiceClient.SetInstanceMachineType(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceSetInstanceMachineType(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetInstanceMachineTypeAsync</summary>
public async Task SetInstanceMachineTypeRequestObjectAsync()
{
// Snippet: SetInstanceMachineTypeAsync(SetInstanceMachineTypeRequest, CallSettings)
// Additional: SetInstanceMachineTypeAsync(SetInstanceMachineTypeRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
SetInstanceMachineTypeRequest request = new SetInstanceMachineTypeRequest
{
Name = "",
MachineType = "",
};
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.SetInstanceMachineTypeAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceSetInstanceMachineTypeAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetInstanceLabels</summary>
public void SetInstanceLabelsRequestObject()
{
// Snippet: SetInstanceLabels(SetInstanceLabelsRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
SetInstanceLabelsRequest request = new SetInstanceLabelsRequest
{
Name = "",
Labels = { { "", "" }, },
};
// Make the request
Operation<Instance, OperationMetadata> response = notebookServiceClient.SetInstanceLabels(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceSetInstanceLabels(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for SetInstanceLabelsAsync</summary>
public async Task SetInstanceLabelsRequestObjectAsync()
{
// Snippet: SetInstanceLabelsAsync(SetInstanceLabelsRequest, CallSettings)
// Additional: SetInstanceLabelsAsync(SetInstanceLabelsRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
SetInstanceLabelsRequest request = new SetInstanceLabelsRequest
{
Name = "",
Labels = { { "", "" }, },
};
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.SetInstanceLabelsAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceSetInstanceLabelsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteInstance</summary>
public void DeleteInstanceRequestObject()
{
// Snippet: DeleteInstance(DeleteInstanceRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
DeleteInstanceRequest request = new DeleteInstanceRequest { Name = "", };
// Make the request
Operation<Empty, OperationMetadata> response = notebookServiceClient.DeleteInstance(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceDeleteInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteInstanceAsync</summary>
public async Task DeleteInstanceRequestObjectAsync()
{
// Snippet: DeleteInstanceAsync(DeleteInstanceRequest, CallSettings)
// Additional: DeleteInstanceAsync(DeleteInstanceRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteInstanceRequest request = new DeleteInstanceRequest { Name = "", };
// Make the request
Operation<Empty, OperationMetadata> response = await notebookServiceClient.DeleteInstanceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceDeleteInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for StartInstance</summary>
public void StartInstanceRequestObject()
{
// Snippet: StartInstance(StartInstanceRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
StartInstanceRequest request = new StartInstanceRequest { Name = "", };
// Make the request
Operation<Instance, OperationMetadata> response = notebookServiceClient.StartInstance(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceStartInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for StartInstanceAsync</summary>
public async Task StartInstanceRequestObjectAsync()
{
// Snippet: StartInstanceAsync(StartInstanceRequest, CallSettings)
// Additional: StartInstanceAsync(StartInstanceRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
StartInstanceRequest request = new StartInstanceRequest { Name = "", };
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.StartInstanceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceStartInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for StopInstance</summary>
public void StopInstanceRequestObject()
{
// Snippet: StopInstance(StopInstanceRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
StopInstanceRequest request = new StopInstanceRequest { Name = "", };
// Make the request
Operation<Instance, OperationMetadata> response = notebookServiceClient.StopInstance(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceStopInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for StopInstanceAsync</summary>
public async Task StopInstanceRequestObjectAsync()
{
// Snippet: StopInstanceAsync(StopInstanceRequest, CallSettings)
// Additional: StopInstanceAsync(StopInstanceRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
StopInstanceRequest request = new StopInstanceRequest { Name = "", };
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.StopInstanceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceStopInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ResetInstance</summary>
public void ResetInstanceRequestObject()
{
// Snippet: ResetInstance(ResetInstanceRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
ResetInstanceRequest request = new ResetInstanceRequest { Name = "", };
// Make the request
Operation<Instance, OperationMetadata> response = notebookServiceClient.ResetInstance(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceResetInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ResetInstanceAsync</summary>
public async Task ResetInstanceRequestObjectAsync()
{
// Snippet: ResetInstanceAsync(ResetInstanceRequest, CallSettings)
// Additional: ResetInstanceAsync(ResetInstanceRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
ResetInstanceRequest request = new ResetInstanceRequest { Name = "", };
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.ResetInstanceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceResetInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ReportInstanceInfo</summary>
public void ReportInstanceInfoRequestObject()
{
// Snippet: ReportInstanceInfo(ReportInstanceInfoRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
ReportInstanceInfoRequest request = new ReportInstanceInfoRequest
{
Name = "",
VmId = "",
Metadata = { { "", "" }, },
};
// Make the request
Operation<Instance, OperationMetadata> response = notebookServiceClient.ReportInstanceInfo(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceReportInstanceInfo(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ReportInstanceInfoAsync</summary>
public async Task ReportInstanceInfoRequestObjectAsync()
{
// Snippet: ReportInstanceInfoAsync(ReportInstanceInfoRequest, CallSettings)
// Additional: ReportInstanceInfoAsync(ReportInstanceInfoRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
ReportInstanceInfoRequest request = new ReportInstanceInfoRequest
{
Name = "",
VmId = "",
Metadata = { { "", "" }, },
};
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.ReportInstanceInfoAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceReportInstanceInfoAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for IsInstanceUpgradeable</summary>
public void IsInstanceUpgradeableRequestObject()
{
// Snippet: IsInstanceUpgradeable(IsInstanceUpgradeableRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
IsInstanceUpgradeableRequest request = new IsInstanceUpgradeableRequest
{
NotebookInstance = "",
};
// Make the request
IsInstanceUpgradeableResponse response = notebookServiceClient.IsInstanceUpgradeable(request);
// End snippet
}
/// <summary>Snippet for IsInstanceUpgradeableAsync</summary>
public async Task IsInstanceUpgradeableRequestObjectAsync()
{
// Snippet: IsInstanceUpgradeableAsync(IsInstanceUpgradeableRequest, CallSettings)
// Additional: IsInstanceUpgradeableAsync(IsInstanceUpgradeableRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
IsInstanceUpgradeableRequest request = new IsInstanceUpgradeableRequest
{
NotebookInstance = "",
};
// Make the request
IsInstanceUpgradeableResponse response = await notebookServiceClient.IsInstanceUpgradeableAsync(request);
// End snippet
}
/// <summary>Snippet for UpgradeInstance</summary>
public void UpgradeInstanceRequestObject()
{
// Snippet: UpgradeInstance(UpgradeInstanceRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
UpgradeInstanceRequest request = new UpgradeInstanceRequest { Name = "", };
// Make the request
Operation<Instance, OperationMetadata> response = notebookServiceClient.UpgradeInstance(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceUpgradeInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpgradeInstanceAsync</summary>
public async Task UpgradeInstanceRequestObjectAsync()
{
// Snippet: UpgradeInstanceAsync(UpgradeInstanceRequest, CallSettings)
// Additional: UpgradeInstanceAsync(UpgradeInstanceRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
UpgradeInstanceRequest request = new UpgradeInstanceRequest { Name = "", };
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.UpgradeInstanceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceUpgradeInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpgradeInstanceInternal</summary>
public void UpgradeInstanceInternalRequestObject()
{
// Snippet: UpgradeInstanceInternal(UpgradeInstanceInternalRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
UpgradeInstanceInternalRequest request = new UpgradeInstanceInternalRequest { Name = "", VmId = "", };
// Make the request
Operation<Instance, OperationMetadata> response = notebookServiceClient.UpgradeInstanceInternal(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceUpgradeInstanceInternal(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpgradeInstanceInternalAsync</summary>
public async Task UpgradeInstanceInternalRequestObjectAsync()
{
// Snippet: UpgradeInstanceInternalAsync(UpgradeInstanceInternalRequest, CallSettings)
// Additional: UpgradeInstanceInternalAsync(UpgradeInstanceInternalRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
UpgradeInstanceInternalRequest request = new UpgradeInstanceInternalRequest { Name = "", VmId = "", };
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.UpgradeInstanceInternalAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceUpgradeInstanceInternalAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ListEnvironments</summary>
public void ListEnvironmentsRequestObject()
{
// Snippet: ListEnvironments(ListEnvironmentsRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
ListEnvironmentsRequest request = new ListEnvironmentsRequest { Parent = "", };
// Make the request
PagedEnumerable<ListEnvironmentsResponse, gcnv::Environment> response = notebookServiceClient.ListEnvironments(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (gcnv::Environment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListEnvironmentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (gcnv::Environment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<gcnv::Environment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (gcnv::Environment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListEnvironmentsAsync</summary>
public async Task ListEnvironmentsRequestObjectAsync()
{
// Snippet: ListEnvironmentsAsync(ListEnvironmentsRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
ListEnvironmentsRequest request = new ListEnvironmentsRequest { Parent = "", };
// Make the request
PagedAsyncEnumerable<ListEnvironmentsResponse, gcnv::Environment> response = notebookServiceClient.ListEnvironmentsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((gcnv::Environment item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListEnvironmentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (gcnv::Environment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<gcnv::Environment> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (gcnv::Environment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetEnvironment</summary>
public void GetEnvironmentRequestObject()
{
// Snippet: GetEnvironment(GetEnvironmentRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
GetEnvironmentRequest request = new GetEnvironmentRequest { Name = "", };
// Make the request
gcnv::Environment response = notebookServiceClient.GetEnvironment(request);
// End snippet
}
/// <summary>Snippet for GetEnvironmentAsync</summary>
public async Task GetEnvironmentRequestObjectAsync()
{
// Snippet: GetEnvironmentAsync(GetEnvironmentRequest, CallSettings)
// Additional: GetEnvironmentAsync(GetEnvironmentRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
GetEnvironmentRequest request = new GetEnvironmentRequest { Name = "", };
// Make the request
gcnv::Environment response = await notebookServiceClient.GetEnvironmentAsync(request);
// End snippet
}
/// <summary>Snippet for CreateEnvironment</summary>
public void CreateEnvironmentRequestObject()
{
// Snippet: CreateEnvironment(CreateEnvironmentRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
CreateEnvironmentRequest request = new CreateEnvironmentRequest
{
Parent = "",
EnvironmentId = "",
Environment = new gcnv::Environment(),
};
// Make the request
Operation<gcnv::Environment, OperationMetadata> response = notebookServiceClient.CreateEnvironment(request);
// Poll until the returned long-running operation is complete
Operation<gcnv::Environment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
gcnv::Environment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcnv::Environment, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceCreateEnvironment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcnv::Environment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateEnvironmentAsync</summary>
public async Task CreateEnvironmentRequestObjectAsync()
{
// Snippet: CreateEnvironmentAsync(CreateEnvironmentRequest, CallSettings)
// Additional: CreateEnvironmentAsync(CreateEnvironmentRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
CreateEnvironmentRequest request = new CreateEnvironmentRequest
{
Parent = "",
EnvironmentId = "",
Environment = new gcnv::Environment(),
};
// Make the request
Operation<gcnv::Environment, OperationMetadata> response = await notebookServiceClient.CreateEnvironmentAsync(request);
// Poll until the returned long-running operation is complete
Operation<gcnv::Environment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
gcnv::Environment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<gcnv::Environment, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceCreateEnvironmentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
gcnv::Environment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteEnvironment</summary>
public void DeleteEnvironmentRequestObject()
{
// Snippet: DeleteEnvironment(DeleteEnvironmentRequest, CallSettings)
// Create client
NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
// Initialize request argument(s)
DeleteEnvironmentRequest request = new DeleteEnvironmentRequest { Name = "", };
// Make the request
Operation<Empty, OperationMetadata> response = notebookServiceClient.DeleteEnvironment(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = notebookServiceClient.PollOnceDeleteEnvironment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteEnvironmentAsync</summary>
public async Task DeleteEnvironmentRequestObjectAsync()
{
// Snippet: DeleteEnvironmentAsync(DeleteEnvironmentRequest, CallSettings)
// Additional: DeleteEnvironmentAsync(DeleteEnvironmentRequest, CancellationToken)
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteEnvironmentRequest request = new DeleteEnvironmentRequest { Name = "", };
// Make the request
Operation<Empty, OperationMetadata> response = await notebookServiceClient.DeleteEnvironmentAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceDeleteEnvironmentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
namespace SerilogAnalyzer
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = nameof(ShowConfigCodeRefactoringProvider)), Shared]
public class ShowConfigCodeRefactoringProvider : CodeRefactoringProvider
{
private static string[] InterestingProperties = { "Destructure", "Enrich", "Filter", "MinimumLevel", "ReadFrom", "WriteTo", "AuditTo" };
private static string[] LogLevels = { "Debug", "Error", "Fatal", "Information", "Verbose", "Warning" };
private const string NotAConstantReplacementValue = "?";
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
// Find the node at the selection.
var node = root.FindNode(context.Span);
// Arcane code for finding the starting node in a fluent syntax - waiting to blow up
var descendants = node.AncestorsAndSelf().OfType<InvocationExpressionSyntax>().LastOrDefault()?.DescendantNodesAndSelf().ToList();
if (descendants == null)
{
return;
}
// From all the syntax in the fluent configuration, grab the properties (WriteTo, ...)
var configurationProperties = descendants.OfType<MemberAccessExpressionSyntax>().Where(x => InterestingProperties.Contains(x.Name.ToString())).ToList();
var firstProperty = configurationProperties.FirstOrDefault();
if (firstProperty == null)
{
return;
}
LoggerConfiguration configuration = GetLoggerConfigurationFromSyntax(context, semanticModel, configurationProperties);
var appSettingsApplicable = configuration.Enrich.Count > 0 || configuration.EnrichWithProperty.Count > 0 || configuration.MinimumLevel != null || configuration.WriteTo.Count > 0 || configuration.Destructure.Count > 0
|| configuration.AuditTo.Count > 0 || configuration.MinimumLevelOverrides.Count > 0 || configuration.Filter.Count > 0 || configuration.MinimumLevelControlledBy != null;
if (appSettingsApplicable)
{
context.RegisterRefactoring(CodeAction.Create("Show <appSettings> config", c => InsertConfigurationComment(context.Document, firstProperty, root, configuration, GetAppSettingsConfiguration, c)));
context.RegisterRefactoring(CodeAction.Create("Show appsettings.json config", c => InsertConfigurationComment(context.Document, firstProperty, root, configuration, GetAppSettingsJsonConfiguration, c)));
}
}
private static LoggerConfiguration GetLoggerConfigurationFromSyntax(CodeRefactoringContext context, SemanticModel semanticModel, List<MemberAccessExpressionSyntax> configurationProperties)
{
var configuration = new LoggerConfiguration();
foreach (var property in configurationProperties)
{
var invokedMethod = property.Ancestors().FirstOrDefault() as MemberAccessExpressionSyntax;
// Just in case we're looking at syntax that has similiar names to LoggerConfiguration (ReadFrom, WriteTo, ...) but isn't related to Serilog
if (invokedMethod == null)
{
continue;
}
if (String.IsNullOrEmpty(invokedMethod?.Name?.ToString()))
{
configuration.AddError("Failed to get name of method", invokedMethod);
continue;
}
string configAction = property.Name.ToString();
if (configAction == "MinimumLevel")
{
string value;
var logLevel = invokedMethod.Name.ToString();
if (logLevel == "Is")
{
// Ask roslyn what's the constant argument value passed to this method
var argument = (invokedMethod?.Parent as InvocationExpressionSyntax)?.ArgumentList?.Arguments.FirstOrDefault();
if (argument == null)
{
configuration.AddError("Can't get parameter value for MinimumLevel.Is(...)", invokedMethod);
continue;
}
var parameter = RoslynHelper.DetermineParameter(argument, semanticModel, false, context.CancellationToken);
if (parameter == null)
{
configuration.AddError("Failed to analyze parameter", argument);
continue;
}
var accessExpression = argument?.Expression as MemberAccessExpressionSyntax;
if (accessExpression == null)
{
configuration.AddError("Failed to analyze parameter", argument);
continue;
}
var constValue = semanticModel.GetConstantValue(accessExpression, context.CancellationToken);
if (!constValue.HasValue)
{
configuration.AddNonConstantError(argument);
continue;
}
long enumIntegralValue;
try
{
enumIntegralValue = Convert.ToInt64(constValue.Value);
}
catch
{
configuration.AddError($"Value {constValue.Value} is not within expected range", argument);
continue;
}
// Roslyn returns enum constant values as integers, convert it back to the enum member name
var enumMember = parameter.Type.GetMembers().OfType<IFieldSymbol>().FirstOrDefault(x => Convert.ToInt64(x.ConstantValue) == enumIntegralValue);
value = enumMember.Name;
}
else if (logLevel == "Override")
{
var arguments = (invokedMethod?.Parent as InvocationExpressionSyntax)?.ArgumentList?.Arguments ?? default(SeparatedSyntaxList<ArgumentSyntax>);
string key = null;
string level = null;
foreach (var argument in arguments)
{
var parameter = RoslynHelper.DetermineParameter(argument, semanticModel, false, context.CancellationToken);
if (parameter == null)
{
configuration.AddError("Failed to analyze parameter", argument);
continue;
}
if (parameter.Name == "source")
{
var constValue = semanticModel.GetConstantValue(argument.Expression, context.CancellationToken);
if (!constValue.HasValue)
{
configuration.AddNonConstantError(argument.Expression);
value = NotAConstantReplacementValue;
continue;
}
key = constValue.Value?.ToString();
}
else if (parameter.Name == "minimumLevel")
{
var constValue = semanticModel.GetConstantValue(argument.Expression, context.CancellationToken);
if (!constValue.HasValue)
{
configuration.AddNonConstantError(argument.Expression);
value = NotAConstantReplacementValue;
continue;
}
var enumMember = parameter.Type.GetMembers().OfType<IFieldSymbol>().FirstOrDefault(x => Convert.ToInt64(x.ConstantValue) == Convert.ToInt64(constValue.Value));
level = enumMember.Name;
}
}
if (key != null && level != null)
{
configuration.MinimumLevelOverrides[key] = level;
}
continue;
}
else if (logLevel == "ControlledBy")
{
var argument = (invokedMethod?.Parent as InvocationExpressionSyntax)?.ArgumentList?.Arguments.FirstOrDefault();
if (argument == null)
{
configuration.AddError("Can't get parameter value for MinimumLevel.ControlledBy(...)", invokedMethod);
continue;
}
var identifier = argument?.Expression as IdentifierNameSyntax;
if (identifier == null)
{
configuration.AddError("Failed to analyze parameter", argument);
continue;
}
TryAddLoggingLevelSwitch(semanticModel, identifier, configuration, context.CancellationToken);
configuration.MinimumLevelControlledBy = "$" + identifier.Identifier.Value;
continue;
}
else if (LogLevels.Contains(logLevel))
{
value = logLevel;
}
else
{
configuration.AddError("Unknown MinimumLevel method", invokedMethod);
continue;
}
configuration.MinimumLevel = value;
}
else if (configAction == "Enrich")
{
if (invokedMethod.Name.ToString() == "WithProperty")
{
var arguments = (invokedMethod?.Parent as InvocationExpressionSyntax)?.ArgumentList?.Arguments ?? default(SeparatedSyntaxList<ArgumentSyntax>);
string key = null;
string value = null;
foreach (var argument in arguments)
{
var parameter = RoslynHelper.DetermineParameter(argument, semanticModel, false, context.CancellationToken);
if (parameter == null)
{
configuration.AddError("Failed to analyze parameter", argument);
continue;
}
if (parameter.Name == "name")
{
var constValue = semanticModel.GetConstantValue(argument.Expression, context.CancellationToken);
if (!constValue.HasValue)
{
configuration.AddNonConstantError(argument.Expression);
value = NotAConstantReplacementValue;
continue;
}
key = constValue.Value?.ToString();
}
else if (parameter.Name == "value")
{
var constValue = semanticModel.GetConstantValue(argument.Expression, context.CancellationToken);
if (!constValue.HasValue)
{
configuration.AddNonConstantError(argument.Expression);
value = NotAConstantReplacementValue;
continue;
}
value = constValue.Value?.ToString();
}
}
if (key != null && value != null)
{
configuration.EnrichWithProperty[key] = value;
}
}
else
{
AddExtensibleMethod(semanticModel, invokedMethod, configuration, configuration.Enrich.Add, context.CancellationToken);
}
}
else if (configAction == "Destructure")
{
AddExtensibleMethod(semanticModel, invokedMethod, configuration, configuration.Destructure.Add, context.CancellationToken);
}
else if (configAction == "Filter")
{
AddExtensibleMethod(semanticModel, invokedMethod, configuration, configuration.Filter.Add, context.CancellationToken);
}
else if (configAction == "WriteTo")
{
AddExtensibleMethod(semanticModel, invokedMethod, configuration, configuration.WriteTo.Add, context.CancellationToken);
}
else if (configAction == "AuditTo")
{
AddExtensibleMethod(semanticModel, invokedMethod, configuration, configuration.AuditTo.Add, context.CancellationToken);
}
}
return configuration;
}
private static void AddExtensibleMethod(SemanticModel semanticModel, MemberAccessExpressionSyntax invokedMethod, LoggerConfiguration configuration, Action<ExtensibleMethod> addMethod, CancellationToken cancellationToken)
{
var methodSymbol = semanticModel.GetSymbolInfo(invokedMethod).Symbol as IMethodSymbol;
var method = new ExtensibleMethod
{
AssemblyName = methodSymbol?.ContainingAssembly?.Name,
MethodName = invokedMethod.Name.Identifier.ToString()
};
if (String.IsNullOrEmpty(method.AssemblyName))
{
configuration.AddError("Failed to get semantic informations for this method", invokedMethod);
return;
}
// Check for explicitly given type arguments that are not part of the normal arguments
if (methodSymbol.TypeArguments.Length > 0 && methodSymbol.TypeArguments.Length == methodSymbol.TypeParameters.Length)
{
for (int i = 0; i < methodSymbol.TypeArguments.Length; i++)
{
var typeParamter = methodSymbol.TypeParameters[i];
var typeArgument = methodSymbol.TypeArguments[i];
if (methodSymbol.Parameters.Any(x => x.Type == typeParamter))
{
continue;
}
// Synthesize an System.Type argument if a generic version was used
switch (typeParamter.Name)
{
case "TSink": // WriteTo/AuditTo.Sink<TSink>(...)
method.Arguments["sink"] = GetAssemblyQualifiedTypeName(typeArgument);
break;
case "TEnricher": // Enrich.With<TEnricher>()
method.Arguments["enricher"] = GetAssemblyQualifiedTypeName(typeArgument);
break;
case "TFilter": // Filter.With<TFilter>()
method.Arguments["filter"] = GetAssemblyQualifiedTypeName(typeArgument);
break;
case "TDestructuringPolicy": // Destructure.With<TDestructuringPolicy>()
method.Arguments["policy"] = GetAssemblyQualifiedTypeName(typeArgument);
break;
case "TScalar": // Destructure.AsScalar<TScalar>()
method.Arguments["scalarType"] = GetAssemblyQualifiedTypeName(typeArgument);
break;
}
}
}
var arguments = (invokedMethod?.Parent as InvocationExpressionSyntax)?.ArgumentList?.Arguments ?? default(SeparatedSyntaxList<ArgumentSyntax>);
foreach (var argument in arguments)
{
var parameter = RoslynHelper.DetermineParameter(argument, semanticModel, false, cancellationToken);
if (parameter == null)
{
configuration.AddError("Failed to analyze parameter", argument);
continue;
}
string parameterName = parameter.Name;
// Configuration Surrogates
if (method.MethodName == "Sink" && parameterName == "logEventSink") // WriteTo/AuditTo.Sink(ILogEventSink logEventSink, ...)
{
parameterName = "sink"; // Sink(this LoggerSinkConfiguration loggerSinkConfiguration, ILogEventSink sink, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, LoggingLevelSwitch levelSwitch = null)
}
else if (method.MethodName == "With" && parameterName == "filters") // Filter.With(params ILogEventFilter[] filters)
{
parameterName = "filter"; // With(this LoggerFilterConfiguration loggerFilterConfiguration, ILogEventFilter filter)
}
else if (method.MethodName == "With" && parameterName == "destructuringPolicies") // Destructure.With(params IDestructuringPolicy[] destructuringPolicies)
{
parameterName = "policy"; // With(this LoggerDestructuringConfiguration loggerDestructuringConfiguration, IDestructuringPolicy policy)
}
else if (method.MethodName == "With" && parameterName == "enrichers") // Enrich.With(params ILogEventEnricher[] enrichers)
{
parameterName = "enricher"; // With(this LoggerEnrichmentConfiguration loggerEnrichmentConfiguration, ILogEventEnricher enricher)
}
ITypeSymbol type = parameter.Type;
if (parameter.IsParams && type is IArrayTypeSymbol array)
{
type = array.ElementType;
}
if (type.ToString() == "System.Type")
{
method.Arguments[parameterName] = NotAConstantReplacementValue;
var typeofExpression = argument.Expression as TypeOfExpressionSyntax;
if (typeofExpression == null)
{
configuration.AddError("I need a typeof(T) expression for Type arguments", argument.Expression);
continue;
}
var typeInfo = semanticModel.GetTypeInfo(typeofExpression.Type).Type as INamedTypeSymbol;
if (typeInfo == null)
{
configuration.AddError("Failed to get semantic informations for typeof expression", typeofExpression);
return;
}
// generate the assembly qualified name for usage with Type.GetType(string)
string name = GetAssemblyQualifiedTypeName(typeInfo);
method.Arguments[parameterName] = name;
continue;
}
else if (type.TypeKind == TypeKind.Interface || type.TypeKind == TypeKind.Class && type.IsAbstract)
{
method.Arguments[parameterName] = NotAConstantReplacementValue;
var expressionSymbol = semanticModel.GetSymbolInfo(argument.Expression).Symbol;
if (expressionSymbol != null && (expressionSymbol.Kind == SymbolKind.Property || expressionSymbol.Kind == SymbolKind.Field))
{
if (!expressionSymbol.IsStatic)
{
configuration.AddError("Only static fields and properties can be used", argument.Expression);
continue;
}
if (expressionSymbol.DeclaredAccessibility != Accessibility.Public || expressionSymbol is IPropertySymbol property && property.GetMethod.DeclaredAccessibility != Accessibility.Public)
{
configuration.AddError("Fields and properties must be public and properties must have public getters", argument.Expression);
continue;
}
method.Arguments[parameterName] = GetAssemblyQualifiedTypeName(expressionSymbol.ContainingType, "::" + expressionSymbol.Name);
continue;
}
var objectCreation = argument.Expression as ObjectCreationExpressionSyntax;
if (objectCreation == null)
{
configuration.AddError("I can only infer types from `new T()` expressions", argument.Expression);
continue;
}
// check if there are explicit arguments which are unsupported
if (objectCreation.ArgumentList?.Arguments.Count > 0)
{
configuration.AddError("The configuration supports only parameterless constructors for interface or abstract type parameters", argument.Expression);
continue;
}
var typeInfo = semanticModel.GetTypeInfo(objectCreation).Type as INamedTypeSymbol;
if (typeInfo == null)
{
configuration.AddError("Failed to get semantic informations for this constructor", objectCreation);
return;
}
// generate the assembly qualified name for usage with Type.GetType(string)
string name = GetAssemblyQualifiedTypeName(typeInfo);
method.Arguments[parameterName] = name;
continue;
}
else if (type.ToString() == "Serilog.Core.LoggingLevelSwitch")
{
var identifier = argument?.Expression as IdentifierNameSyntax;
if (identifier == null)
{
configuration.AddError("Failed to analyze parameter", argument);
continue;
}
TryAddLoggingLevelSwitch(semanticModel, identifier, configuration, cancellationToken);
method.Arguments[parameterName] = "$" + identifier.Identifier.Value;
continue;
}
string value = null;
var constValue = semanticModel.GetConstantValue(argument.Expression, cancellationToken);
if (!constValue.HasValue)
{
configuration.AddNonConstantError(argument.Expression);
value = NotAConstantReplacementValue;
}
else
{
if (type.TypeKind == TypeKind.Enum)
{
var enumMember = type.GetMembers().OfType<IFieldSymbol>().FirstOrDefault(x => Convert.ToInt64(x.ConstantValue) == Convert.ToInt64(constValue.Value));
value = enumMember.Name;
}
else
{
value = constValue.Value?.ToString();
}
}
method.Arguments[parameterName] = value;
}
addMethod(method);
}
private static void TryAddLoggingLevelSwitch(SemanticModel semanticModel, IdentifierNameSyntax identifier, LoggerConfiguration configuration, CancellationToken cancellationToken)
{
string name = "$" + identifier.Identifier.Value;
if (configuration.LevelSwitches.ContainsKey(name))
{
return;
}
var symbol = semanticModel.GetSymbolInfo(identifier, cancellationToken).Symbol;
if (symbol == null)
{
configuration.AddError("Failed to analyze parameter", identifier);
return;
}
var reference = symbol.DeclaringSyntaxReferences.FirstOrDefault() as SyntaxReference;
if (reference == null)
{
configuration.AddError("Could not find declaration of LoggingLevelSwitch", identifier);
return;
}
var declarator = reference.GetSyntax(cancellationToken) as VariableDeclaratorSyntax;
if (declarator == null)
{
configuration.AddError("Could not find declaration of LoggingLevelSwitch", identifier);
return;
}
var initializer = declarator.Initializer.Value as ObjectCreationExpressionSyntax;
if (initializer == null)
{
configuration.AddError("Could not find initialization of LoggingLevelSwitch", identifier);
return;
}
IParameterSymbol parameter;
object value;
var argument = initializer.ArgumentList.Arguments.FirstOrDefault();
if (argument == null)
{
var constructor = semanticModel.GetSymbolInfo(initializer, cancellationToken).Symbol;
if (constructor == null)
{
configuration.AddError("Could not analyze LoggingLevelSwitch constructor", identifier);
return;
}
parameter = (symbol as IMethodSymbol)?.Parameters.FirstOrDefault();
if (parameter == null)
{
configuration.AddError("Could not analyze LoggingLevelSwitch constructor", identifier);
return;
}
value = parameter.ExplicitDefaultValue;
}
else
{
parameter = RoslynHelper.DetermineParameter(argument, semanticModel, false, cancellationToken);
if (parameter == null)
{
configuration.AddError("Failed to analyze parameter", argument);
return;
}
var constValue = semanticModel.GetConstantValue(argument.Expression, cancellationToken);
if (!constValue.HasValue)
{
configuration.AddNonConstantError(argument);
return;
}
value = constValue.Value;
}
long enumIntegralValue;
try
{
enumIntegralValue = Convert.ToInt64(value);
}
catch
{
configuration.AddError($"Value {value} is not within expected range", argument);
return;
}
// Roslyn returns enum constant values as integers, convert it back to the enum member name
var enumMember = parameter.Type.GetMembers().OfType<IFieldSymbol>().FirstOrDefault(x => Convert.ToInt64(x.ConstantValue) == enumIntegralValue);
configuration.LevelSwitches.Add(name, enumMember.Name);
}
private static string GetAssemblyQualifiedTypeName(ITypeSymbol type, string typeSuffix = null)
{
var display = new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);
string name = type.ToDisplayString(display);
var namedType = type as INamedTypeSymbol;
if (namedType?.TypeArguments.Length > 0)
{
name += "`" + namedType.Arity;
name += "[" + String.Join(", ", namedType.TypeArguments.Select(x => "[" + GetAssemblyQualifiedTypeName(x) + "]")) + "]";
}
if (typeSuffix != null)
{
name += typeSuffix;
}
name += ", " + type.ContainingAssembly.ToString();
return name;
}
private Task<Document> InsertConfigurationComment(Document document, MemberAccessExpressionSyntax firstProperty, SyntaxNode root, LoggerConfiguration configuration, Func<LoggerConfiguration, string> generateConfig, CancellationToken cancellationToken)
{
var trivia = SyntaxFactory.ParseTrailingTrivia(generateConfig(configuration));
var statement = firstProperty.AncestorsAndSelf().OfType<StatementSyntax>().FirstOrDefault();
var newStatement = statement.WithLeadingTrivia(statement.GetLeadingTrivia().InsertRange(0, trivia)).WithAdditionalAnnotations(Formatter.Annotation);
var newRoot = root.ReplaceNode(statement, newStatement);
var newDocument = document.WithSyntaxRoot(newRoot);
return Task.FromResult(newDocument);
}
private static string GetAppSettingsConfiguration(LoggerConfiguration configuration)
{
var configEntries = new List<XElement>();
foreach (var kvp in configuration.LevelSwitches)
{
AddEntry(configEntries, "serilog:level-switch:" + kvp.Key, kvp.Value);
}
if (configuration.MinimumLevel != null)
{
AddEntry(configEntries, "serilog:minimum-level", configuration.MinimumLevel);
}
if (configuration.MinimumLevelControlledBy != null)
{
AddEntry(configEntries, "serilog:minimum-level:controlled-by", configuration.MinimumLevelControlledBy);
}
foreach (var kvp in configuration.MinimumLevelOverrides)
{
AddEntry(configEntries, "serilog:minimum-level:override:" + kvp.Key, kvp.Value);
}
foreach (var kvp in configuration.EnrichWithProperty)
{
AddEntry(configEntries, "serilog:enrich:with-property:" + kvp.Key, kvp.Value);
}
foreach (var enrichment in configuration.Enrich)
{
ConvertExtensibleMethod(configEntries, enrichment, "serilog:enrich");
}
foreach (var filter in configuration.Filter)
{
ConvertExtensibleMethod(configEntries, filter, "serilog:filter");
}
foreach (var destructure in configuration.Destructure)
{
ConvertExtensibleMethod(configEntries, destructure, "serilog:destructure");
}
foreach (var writeTo in configuration.WriteTo)
{
ConvertExtensibleMethod(configEntries, writeTo, "serilog:write-to");
}
foreach (var auditTo in configuration.AuditTo)
{
ConvertExtensibleMethod(configEntries, auditTo, "serilog:audit-to");
}
var usedSuffixes = new HashSet<string>();
foreach (var usedAssembly in configuration.Enrich.Concat(configuration.WriteTo).Concat(configuration.AuditTo).Select(x => x.AssemblyName).Where(x => x != "Serilog").Distinct())
{
if (usedAssembly != "Serilog")
{
var parts = usedAssembly.Split('.');
var suffix = parts.Last();
if (!usedSuffixes.Add(suffix))
suffix = String.Join("", parts);
AddEntry(configEntries, $"serilog:using:{suffix}", usedAssembly);
}
}
var sb = new StringBuilder();
sb.AppendLine("/*");
if (configuration.HasParsingErrors)
{
sb.AppendLine("Errors:");
foreach (var log in configuration.ErrorLog)
{
sb.AppendLine(log);
}
if (configuration.ErrorLog.Count > 0)
{
sb.AppendLine();
}
}
foreach (var entry in configEntries)
{
sb.AppendLine(entry.ToString());
}
sb.AppendLine("*/");
return sb.ToString();
}
private static void ConvertExtensibleMethod(List<XElement> configEntries, ExtensibleMethod enrichment, string prefix)
{
string key = $"{prefix}:{enrichment.MethodName}";
if (!enrichment.Arguments.Any())
{
AddEntry(configEntries, key, null);
return;
}
foreach (var argument in enrichment.Arguments)
{
AddEntry(configEntries, $"{key}.{argument.Key}", argument.Value);
}
}
private static void AddEntry(List<XElement> configEntries, string key, string value)
{
if (value != null)
{
configEntries.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", value)));
}
else
{
configEntries.Add(new XElement("add", new XAttribute("key", key)));
}
}
private static string GetAppSettingsJsonConfiguration(LoggerConfiguration configuration)
{
var sb = new StringBuilder();
sb.AppendLine("/*");
if (configuration.HasParsingErrors)
{
sb.AppendLine("Errors:");
foreach (var log in configuration.ErrorLog)
{
sb.AppendLine(log);
}
sb.AppendLine();
}
sb.AppendLine(@"""Serilog"": {");
bool needsComma = false;
// technically it's not correct to abuse roslyn to escape the string literals for us but csharp strings look very much like js string literals so...
string usings = String.Join(", ", configuration.Enrich.Concat(configuration.WriteTo).Concat(configuration.AuditTo).Select(x => x.AssemblyName).Where(x => x != "Serilog").Distinct().Select(x => SyntaxFactory.Literal(x).ToString()));
if (!String.IsNullOrEmpty(usings))
{
sb.AppendFormat(@" ""Using"": [{0}]", usings);
needsComma = true;
}
if (configuration.LevelSwitches.Count > 0)
{
FinishPreviousLine(sb, ref needsComma);
string switches = String.Join(", ", configuration.LevelSwitches.Select(x => SyntaxFactory.Literal(x.Key).ToString() + ": " + SyntaxFactory.Literal(x.Value).ToString()));
sb.AppendFormat(@" ""LevelSwitches"": {{ {0} }}", switches);
needsComma = true;
}
if (configuration.MinimumLevel != null || configuration.MinimumLevelControlledBy != null || configuration.MinimumLevelOverrides.Any())
{
FinishPreviousLine(sb, ref needsComma);
if (!configuration.MinimumLevelOverrides.Any() && configuration.MinimumLevelControlledBy == null)
{
sb.AppendFormat(@" ""MinimumLevel"": {0}", SyntaxFactory.Literal(configuration.MinimumLevel).ToString());
}
else
{
sb.AppendLine(@" ""MinimumLevel"": {");
if (configuration.MinimumLevel != null)
{
sb.AppendFormat(@" ""Default"": {0}", SyntaxFactory.Literal(configuration.MinimumLevel).ToString());
needsComma = true;
}
if (configuration.MinimumLevelControlledBy != null)
{
FinishPreviousLine(sb, ref needsComma);
sb.AppendFormat(@" ""ControlledBy"": {0}", SyntaxFactory.Literal(configuration.MinimumLevelControlledBy).ToString());
needsComma = true;
}
int remaining = configuration.MinimumLevelOverrides.Count;
if (remaining > 0)
{
FinishPreviousLine(sb, ref needsComma);
sb.AppendLine(@" ""Override"": {");
foreach (var levelOverride in configuration.MinimumLevelOverrides)
{
sb.AppendFormat(" {0}: {1}", SyntaxFactory.Literal(levelOverride.Key).ToString(), SyntaxFactory.Literal(levelOverride.Value).ToString());
if (--remaining > 0)
{
sb.AppendLine(",");
}
else
{
sb.AppendLine();
}
}
sb.AppendLine(@" }");
}
else
{
sb.AppendLine();
}
sb.Append(@" }");
}
needsComma = true;
}
if (configuration.WriteTo.Any())
{
FinishPreviousLine(sb, ref needsComma);
WriteMethodCalls(configuration.WriteTo, sb, "WriteTo");
needsComma = true;
}
if (configuration.AuditTo.Any())
{
FinishPreviousLine(sb, ref needsComma);
WriteMethodCalls(configuration.AuditTo, sb, "AuditTo");
needsComma = true;
}
if (configuration.Enrich.Any())
{
FinishPreviousLine(sb, ref needsComma);
WriteMethodCalls(configuration.Enrich, sb, "Enrich");
needsComma = true;
}
if (configuration.Destructure.Any())
{
FinishPreviousLine(sb, ref needsComma);
WriteMethodCalls(configuration.Destructure, sb, "Destructure");
needsComma = true;
}
if (configuration.Filter.Any())
{
FinishPreviousLine(sb, ref needsComma);
WriteMethodCalls(configuration.Filter, sb, "Filter");
needsComma = true;
}
if (configuration.EnrichWithProperty.Any())
{
FinishPreviousLine(sb, ref needsComma);
sb.AppendLine(@" ""Properties"": {");
int remaining = configuration.EnrichWithProperty.Count;
foreach (var property in configuration.EnrichWithProperty)
{
sb.AppendFormat(" {0}: {1}", SyntaxFactory.Literal(property.Key).ToString(), SyntaxFactory.Literal(property.Value).ToString());
if (--remaining > 0)
{
sb.AppendLine(",");
}
else
{
sb.AppendLine();
}
}
sb.Append(@" }");
needsComma = true;
}
sb.AppendLine();
sb.AppendLine(@"}");
sb.AppendLine("*/");
return sb.ToString();
}
private static void WriteMethodCalls(List<ExtensibleMethod> methods, StringBuilder sb, string methodKind)
{
sb.AppendFormat(@" ""{0}"": [", methodKind);
if (methods.All(x => !x.Arguments.Any()))
{
sb.Append(String.Join(", ", methods.Select(x => SyntaxFactory.Literal(x.MethodName).ToString())));
sb.Append("]");
}
else
{
sb.AppendLine();
bool writeToNeedsComma = false;
foreach (var writeTo in methods)
{
FinishPreviousLine(sb, ref writeToNeedsComma);
sb.AppendFormat(@" {{ ""Name"": {0}", SyntaxFactory.Literal(writeTo.MethodName).ToString());
if (writeTo.Arguments.Any())
{
sb.Append(@", ""Args"": { ");
int remaining = writeTo.Arguments.Count;
foreach (var argument in writeTo.Arguments)
{
sb.AppendFormat("{0}: ", SyntaxFactory.Literal(argument.Key).ToString());
if (argument.Value == null)
{
sb.Append("null");
}
else
{
sb.Append(SyntaxFactory.Literal(argument.Value).ToString());
}
if (--remaining > 0)
{
sb.Append(", ");
}
}
sb.Append(" }");
}
sb.Append(" }");
writeToNeedsComma = true;
}
sb.AppendLine();
sb.Append(@" ]");
}
}
private static void FinishPreviousLine(StringBuilder sb, ref bool needsComma)
{
if (needsComma)
{
sb.AppendLine(",");
needsComma = false;
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Text.Util.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Android.Text.Util
{
/// <summary>
/// <para>This class works as a Tokenizer for MultiAutoCompleteTextView for address list fields, and also provides a method for converting a string of addresses (such as might be typed into such a field) into a series of Rfc822Tokens. </para>
/// </summary>
/// <java-name>
/// android/text/util/Rfc822Tokenizer
/// </java-name>
[Dot42.DexImport("android/text/util/Rfc822Tokenizer", AccessFlags = 33)]
public partial class Rfc822Tokenizer : global::Android.Widget.MultiAutoCompleteTextView.ITokenizer
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Rfc822Tokenizer() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>This constructor will try to take a string like "Foo Bar (something) &lt;foo\@google.com&gt;, blah\@google.com (something)" and convert it into one or more Rfc822Tokens, output into the supplied collection.</para><para>It does <b>not</b> decode MIME encoded-words; charset conversion must already have taken place if necessary. It will try to be tolerant of broken syntax instead of returning an error. </para>
/// </summary>
/// <java-name>
/// tokenize
/// </java-name>
[Dot42.DexImport("tokenize", "(Ljava/lang/CharSequence;Ljava/util/Collection;)V", AccessFlags = 9, Signature = "(Ljava/lang/CharSequence;Ljava/util/Collection<Landroid/text/util/Rfc822Token;>;)" +
"V")]
public static void Tokenize(global::Java.Lang.ICharSequence text, global::Java.Util.ICollection<global::Android.Text.Util.Rfc822Token> @out) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>This method will try to take a string like "Foo Bar (something) &lt;foo\@google.com&gt;, blah\@google.com (something)" and convert it into one or more Rfc822Tokens. It does <b>not</b> decode MIME encoded-words; charset conversion must already have taken place if necessary. It will try to be tolerant of broken syntax instead of returning an error. </para>
/// </summary>
/// <java-name>
/// tokenize
/// </java-name>
[Dot42.DexImport("tokenize", "(Ljava/lang/CharSequence;)[Landroid/text/util/Rfc822Token;", AccessFlags = 9)]
public static global::Android.Text.Util.Rfc822Token[] Tokenize(global::Java.Lang.ICharSequence text) /* MethodBuilder.Create */
{
return default(global::Android.Text.Util.Rfc822Token[]);
}
/// <summary>
/// <para><para>Returns the start of the token that ends at offset <code>cursor</code> within <code>text</code>.</para> </para>
/// </summary>
/// <java-name>
/// findTokenStart
/// </java-name>
[Dot42.DexImport("findTokenStart", "(Ljava/lang/CharSequence;I)I", AccessFlags = 1)]
public virtual int FindTokenStart(global::Java.Lang.ICharSequence text, int cursor) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para><para>Returns the end of the token (minus trailing punctuation) that begins at offset <code>cursor</code> within <code>text</code>.</para> </para>
/// </summary>
/// <java-name>
/// findTokenEnd
/// </java-name>
[Dot42.DexImport("findTokenEnd", "(Ljava/lang/CharSequence;I)I", AccessFlags = 1)]
public virtual int FindTokenEnd(global::Java.Lang.ICharSequence text, int cursor) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Terminates the specified address with a comma and space. This assumes that the specified text already has valid syntax. The Adapter subclass's convertToString() method must make that guarantee. </para>
/// </summary>
/// <java-name>
/// terminateToken
/// </java-name>
[Dot42.DexImport("terminateToken", "(Ljava/lang/CharSequence;)Ljava/lang/CharSequence;", AccessFlags = 1)]
public virtual global::Java.Lang.ICharSequence TerminateToken(global::Java.Lang.ICharSequence text) /* MethodBuilder.Create */
{
return default(global::Java.Lang.ICharSequence);
}
}
/// <summary>
/// <para>This class stores an RFC 822-like name, address, and comment, and provides methods to convert them to quoted strings. </para>
/// </summary>
/// <java-name>
/// android/text/util/Rfc822Token
/// </java-name>
[Dot42.DexImport("android/text/util/Rfc822Token", AccessFlags = 33)]
public partial class Rfc822Token
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new Rfc822Token with the specified name, address, and comment. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public Rfc822Token(string name, string address, string comment) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the name part. </para>
/// </summary>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the address part. </para>
/// </summary>
/// <java-name>
/// getAddress
/// </java-name>
[Dot42.DexImport("getAddress", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetAddress() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the comment part. </para>
/// </summary>
/// <java-name>
/// getComment
/// </java-name>
[Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetComment() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Changes the name to the specified name. </para>
/// </summary>
/// <java-name>
/// setName
/// </java-name>
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetName(string name) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Changes the address to the specified address. </para>
/// </summary>
/// <java-name>
/// setAddress
/// </java-name>
[Dot42.DexImport("setAddress", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetAddress(string address) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Changes the comment to the specified comment. </para>
/// </summary>
/// <java-name>
/// setComment
/// </java-name>
[Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetComment(string comment) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the name (with quoting added if necessary), the comment (in parentheses), and the address (in angle brackets). This should be suitable for inclusion in an RFC 822 address list. </para>
/// </summary>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the name, conservatively quoting it if there are any characters that are likely to cause trouble outside of a quoted string, or returning it literally if it seems safe. </para>
/// </summary>
/// <java-name>
/// quoteNameIfNecessary
/// </java-name>
[Dot42.DexImport("quoteNameIfNecessary", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)]
public static string QuoteNameIfNecessary(string name) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the name, with internal backslashes and quotation marks preceded by backslashes. The outer quote marks themselves are not added by this method. </para>
/// </summary>
/// <java-name>
/// quoteName
/// </java-name>
[Dot42.DexImport("quoteName", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)]
public static string QuoteName(string name) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the comment, with internal backslashes and parentheses preceded by backslashes. The outer parentheses themselves are not added by this method. </para>
/// </summary>
/// <java-name>
/// quoteComment
/// </java-name>
[Dot42.DexImport("quoteComment", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)]
public static string QuoteComment(string comment) /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object o) /* MethodBuilder.Create */
{
return default(bool);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal Rfc822Token() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns the name part. </para>
/// </summary>
/// <java-name>
/// getName
/// </java-name>
public string Name
{
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetName(); }
[Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetName(value); }
}
/// <summary>
/// <para>Returns the address part. </para>
/// </summary>
/// <java-name>
/// getAddress
/// </java-name>
public string Address
{
[Dot42.DexImport("getAddress", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetAddress(); }
[Dot42.DexImport("setAddress", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetAddress(value); }
}
/// <summary>
/// <para>Returns the comment part. </para>
/// </summary>
/// <java-name>
/// getComment
/// </java-name>
public string Comment
{
[Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetComment(); }
[Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetComment(value); }
}
}
/// <summary>
/// <para>Linkify take a piece of text and a regular expression and turns all of the regex matches in the text into clickable links. This is particularly useful for matching things like email addresses, web urls, etc. and making them actionable.</para><para>Alone with the pattern that is to be matched, a url scheme prefix is also required. Any pattern match that does not begin with the supplied scheme will have the scheme prepended to the matched text when the clickable url is created. For instance, if you are matching web urls you would supply the scheme <code></code>. If the pattern matches example.com, which does not have a url scheme prefix, the supplied scheme will be prepended to create <code></code> when the clickable url link is created. </para>
/// </summary>
/// <java-name>
/// android/text/util/Linkify
/// </java-name>
[Dot42.DexImport("android/text/util/Linkify", AccessFlags = 33)]
public partial class Linkify
/* scope: __dot42__ */
{
/// <summary>
/// <para>Bit field indicating that web URLs should be matched in methods that take an options mask </para>
/// </summary>
/// <java-name>
/// WEB_URLS
/// </java-name>
[Dot42.DexImport("WEB_URLS", "I", AccessFlags = 25)]
public const int WEB_URLS = 1;
/// <summary>
/// <para>Bit field indicating that email addresses should be matched in methods that take an options mask </para>
/// </summary>
/// <java-name>
/// EMAIL_ADDRESSES
/// </java-name>
[Dot42.DexImport("EMAIL_ADDRESSES", "I", AccessFlags = 25)]
public const int EMAIL_ADDRESSES = 2;
/// <summary>
/// <para>Bit field indicating that phone numbers should be matched in methods that take an options mask </para>
/// </summary>
/// <java-name>
/// PHONE_NUMBERS
/// </java-name>
[Dot42.DexImport("PHONE_NUMBERS", "I", AccessFlags = 25)]
public const int PHONE_NUMBERS = 4;
/// <summary>
/// <para>Bit field indicating that street addresses should be matched in methods that take an options mask </para>
/// </summary>
/// <java-name>
/// MAP_ADDRESSES
/// </java-name>
[Dot42.DexImport("MAP_ADDRESSES", "I", AccessFlags = 25)]
public const int MAP_ADDRESSES = 8;
/// <summary>
/// <para>Bit mask indicating that all available patterns should be matched in methods that take an options mask </para>
/// </summary>
/// <java-name>
/// ALL
/// </java-name>
[Dot42.DexImport("ALL", "I", AccessFlags = 25)]
public const int ALL = 15;
/// <summary>
/// <para>Filters out web URL matches that occur after an at-sign (@). This is to prevent turning the domain name in an email address into a web link. </para>
/// </summary>
/// <java-name>
/// sUrlMatchFilter
/// </java-name>
[Dot42.DexImport("sUrlMatchFilter", "Landroid/text/util/Linkify$MatchFilter;", AccessFlags = 25)]
public static readonly global::Android.Text.Util.Linkify.IMatchFilter SUrlMatchFilter;
/// <summary>
/// <para>Filters out URL matches that don't have enough digits to be a phone number. </para>
/// </summary>
/// <java-name>
/// sPhoneNumberMatchFilter
/// </java-name>
[Dot42.DexImport("sPhoneNumberMatchFilter", "Landroid/text/util/Linkify$MatchFilter;", AccessFlags = 25)]
public static readonly global::Android.Text.Util.Linkify.IMatchFilter SPhoneNumberMatchFilter;
/// <summary>
/// <para>Transforms matched phone number text into something suitable to be used in a tel: URL. It does this by removing everything but the digits and plus signs. For instance: '+1 (919) 555-1212' becomes '+19195551212' </para>
/// </summary>
/// <java-name>
/// sPhoneNumberTransformFilter
/// </java-name>
[Dot42.DexImport("sPhoneNumberTransformFilter", "Landroid/text/util/Linkify$TransformFilter;", AccessFlags = 25)]
public static readonly global::Android.Text.Util.Linkify.ITransformFilter SPhoneNumberTransformFilter;
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public Linkify() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Scans the text of the provided Spannable and turns all occurrences of the link types indicated in the mask into clickable links. If the mask is nonzero, it also removes any existing URLSpans attached to the Spannable, to avoid problems if you call it repeatedly on the same text. </para>
/// </summary>
/// <java-name>
/// addLinks
/// </java-name>
[Dot42.DexImport("addLinks", "(Landroid/text/Spannable;I)Z", AccessFlags = 25)]
public static bool AddLinks(global::Android.Text.ISpannable text, int mask) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Scans the text of the provided Spannable and turns all occurrences of the link types indicated in the mask into clickable links. If the mask is nonzero, it also removes any existing URLSpans attached to the Spannable, to avoid problems if you call it repeatedly on the same text. </para>
/// </summary>
/// <java-name>
/// addLinks
/// </java-name>
[Dot42.DexImport("addLinks", "(Landroid/widget/TextView;I)Z", AccessFlags = 25)]
public static bool AddLinks(global::Android.Widget.TextView text, int mask) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// addLinks
/// </java-name>
[Dot42.DexImport("addLinks", "(Landroid/widget/TextView;Ljava/util/regex/Pattern;Ljava/lang/String;)V", AccessFlags = 25)]
public static void AddLinks(global::Android.Widget.TextView textView, global::Java.Util.Regex.Pattern pattern, string @string) /* MethodBuilder.Create */
{
}
/// <java-name>
/// addLinks
/// </java-name>
[Dot42.DexImport("addLinks", "(Landroid/widget/TextView;Ljava/util/regex/Pattern;Ljava/lang/String;Landroid/tex" +
"t/util/Linkify$MatchFilter;Landroid/text/util/Linkify$TransformFilter;)V", AccessFlags = 25)]
public static void AddLinks(global::Android.Widget.TextView textView, global::Java.Util.Regex.Pattern pattern, string @string, global::Android.Text.Util.Linkify.IMatchFilter matchFilter, global::Android.Text.Util.Linkify.ITransformFilter transformFilter) /* MethodBuilder.Create */
{
}
/// <java-name>
/// addLinks
/// </java-name>
[Dot42.DexImport("addLinks", "(Landroid/text/Spannable;Ljava/util/regex/Pattern;Ljava/lang/String;)Z", AccessFlags = 25)]
public static bool AddLinks(global::Android.Text.ISpannable spannable, global::Java.Util.Regex.Pattern pattern, string @string) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// addLinks
/// </java-name>
[Dot42.DexImport("addLinks", "(Landroid/text/Spannable;Ljava/util/regex/Pattern;Ljava/lang/String;Landroid/text" +
"/util/Linkify$MatchFilter;Landroid/text/util/Linkify$TransformFilter;)Z", AccessFlags = 25)]
public static bool AddLinks(global::Android.Text.ISpannable spannable, global::Java.Util.Regex.Pattern pattern, string @string, global::Android.Text.Util.Linkify.IMatchFilter matchFilter, global::Android.Text.Util.Linkify.ITransformFilter transformFilter) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>TransformFilter enables client code to have more control over how matched patterns are represented as URLs.</para><para>For example: when converting a phone number such as (919) 555-1212 into a tel: URL the parentheses, white space, and hyphen need to be removed to produce tel:9195551212. </para>
/// </summary>
/// <java-name>
/// android/text/util/Linkify$TransformFilter
/// </java-name>
[Dot42.DexImport("android/text/util/Linkify$TransformFilter", AccessFlags = 1545)]
public partial interface ITransformFilter
/* scope: __dot42__ */
{
/// <summary>
/// <para>Examines the matched text and either passes it through or uses the data in the Matcher state to produce a replacement.</para><para></para>
/// </summary>
/// <returns>
/// <para>The transformed form of the URL </para>
/// </returns>
/// <java-name>
/// transformUrl
/// </java-name>
[Dot42.DexImport("transformUrl", "(Ljava/util/regex/Matcher;Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)]
string TransformUrl(global::Java.Util.Regex.Matcher match, string url) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>MatchFilter enables client code to have more control over what is allowed to match and become a link, and what is not.</para><para>For example: when matching web urls you would like things like to match, as well as just example.com itelf. However, you would not want to match against the domain in . So, when matching against a web url pattern you might also include a MatchFilter that disallows the match if it is immediately preceded by an at-sign (@). </para>
/// </summary>
/// <java-name>
/// android/text/util/Linkify$MatchFilter
/// </java-name>
[Dot42.DexImport("android/text/util/Linkify$MatchFilter", AccessFlags = 1545)]
public partial interface IMatchFilter
/* scope: __dot42__ */
{
/// <summary>
/// <para>Examines the character span matched by the pattern and determines if the match should be turned into an actionable link.</para><para></para>
/// </summary>
/// <returns>
/// <para>Whether this match should be turned into a link </para>
/// </returns>
/// <java-name>
/// acceptMatch
/// </java-name>
[Dot42.DexImport("acceptMatch", "(Ljava/lang/CharSequence;II)Z", AccessFlags = 1025)]
bool AcceptMatch(global::Java.Lang.ICharSequence s, int start, int end) /* MethodBuilder.Create */ ;
}
}
}
| |
//! \file ImageIAF.cs
//! \date Sun May 31 21:17:54 2015
//! \brief IAF image format.
//
// Copyright (C) 2015-2016 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using GameRes.Compression;
using GameRes.Utility;
namespace GameRes.Formats.Triangle
{
internal class IafMetaData : ImageMetaData
{
public int DataOffset;
public int PackedSize;
public int UnpackedSize;
public int PackType;
}
[Export(typeof(ImageFormat))]
public class IafFormat : ImageFormat
{
public override string Tag { get { return "IAF"; } }
public override string Description { get { return "Triangle compressed bitmap format"; } }
public override uint Signature { get { return 0; } }
public override bool CanWrite { get { return false; } }
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = new byte[0x14];
if (12 != stream.Read (header, 0, 12))
return null;
int packed_size0 = LittleEndian.ToInt32 (header, 0);
int packed_size1 = LittleEndian.ToInt32 (header, 1);
int data_offset, packed_size, unpacked_pos;
int tail_size = 0;
if (5+packed_size1+0x14 == stream.Length)
{
packed_size = packed_size1;
data_offset = 5;
tail_size = 0x14;
unpacked_pos = 0x10;
}
else if (5+packed_size1+0xC == stream.Length)
{
packed_size = packed_size1;
data_offset = 5;
tail_size = 12;
unpacked_pos = 8;
}
else if (4+packed_size0+0xC == stream.Length)
{
packed_size = packed_size0;
data_offset = 4;
tail_size = 12;
unpacked_pos = 8;
}
else
{
packed_size = (int)stream.Length-12;
data_offset = 12;
unpacked_pos = 8;
}
if (tail_size > 0)
{
stream.Seek (-tail_size, SeekOrigin.End);
if (tail_size != stream.Read (header, 0, tail_size))
return null;
}
int x = LittleEndian.ToInt32 (header, 0);
int y = LittleEndian.ToInt32 (header, 4);
if (Math.Abs (x) > 4096 || Math.Abs (y) > 4096)
return null;
int unpacked_size = LittleEndian.ToInt32 (header, unpacked_pos);
int pack_type = (unpacked_size >> 30) & 3;
if (3 == pack_type)
return null;
unpacked_size &= (int)~0xC0000000;
stream.Position = data_offset;
byte[] bmp = UnpackBitmap (stream.AsStream, pack_type, packed_size, 0x26);
if (bmp[0] != 'B' && bmp[0] != 'C' || bmp[1] != 'M')
return null;
return new IafMetaData
{
Width = LittleEndian.ToUInt32 (bmp, 0x12),
Height = LittleEndian.ToUInt32 (bmp, 0x16),
OffsetX = x,
OffsetY = y,
BPP = LittleEndian.ToInt16 (bmp, 0x1c),
DataOffset = data_offset,
PackedSize = packed_size,
UnpackedSize = unpacked_size,
PackType = pack_type,
};
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var meta = (IafMetaData)info;
stream.Position = meta.DataOffset;
var bitmap = UnpackBitmap (stream.AsStream, meta.PackType, meta.PackedSize, meta.UnpackedSize);
if ('C' == bitmap[0])
{
bitmap[0] = (byte)'B';
if (info.BPP > 8)
bitmap = ConvertCM (bitmap, (int)info.Width, (int)info.Height, info.BPP);
}
if (info.BPP >= 24) // currently alpha channel could be applied to 24+bpp bitmaps only
{
try
{
int bmp_size = LittleEndian.ToInt32 (bitmap, 2);
if (bitmap.Length - bmp_size > 0x36) // size of bmp header
{
if ('B' == bitmap[bmp_size] && 'M' == bitmap[bmp_size+1] &&
8 == bitmap[bmp_size+0x1c]) // 8bpp
{
uint alpha_width = LittleEndian.ToUInt32 (bitmap, bmp_size+0x12);
uint alpha_height = LittleEndian.ToUInt32 (bitmap, bmp_size+0x16);
if (info.Width == alpha_width && info.Height == alpha_height)
return BitmapWithAlphaChannel (info, bitmap, bmp_size);
}
}
}
catch
{
// ignore any errors occured during alpha-channel read attempt,
// fallback to a plain bitmap
}
}
using (var bmp = new BinMemoryStream (bitmap, stream.Name))
return Bmp.Read (bmp, info);
}
internal static byte[] UnpackBitmap (Stream stream, int pack_type, int packed_size, int unpacked_size)
{
if (2 == pack_type)
{
using (var reader = new RleReader (stream, packed_size, unpacked_size))
{
reader.Unpack();
return reader.Data;
}
}
else if (0 == pack_type)
{
using (var reader = new LzssReader (stream, packed_size, unpacked_size))
{
reader.Unpack();
return reader.Data;
}
}
else if (1 == pack_type)
{
var bitmap = new byte[unpacked_size];
if (bitmap.Length != stream.Read (bitmap, 0, bitmap.Length))
throw new InvalidFormatException ("Unexpected end of file");
return bitmap;
}
else
throw new InvalidFormatException();
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("IafFormat.Write not implemented");
}
static ImageData BitmapWithAlphaChannel (ImageMetaData info, byte[] bitmap, int alpha_offset)
{
int info_offset = alpha_offset+0x0E;
int palette_offset = info_offset + LittleEndian.ToInt32 (bitmap, info_offset);
int src_pixels = LittleEndian.ToInt32 (bitmap, 0x0A);
int src_alpha = alpha_offset + LittleEndian.ToInt32 (bitmap, alpha_offset+0x0A);
int colors = (src_alpha - palette_offset) / 4;
var alpha_map = new byte[0x100];
if (colors > 0)
{
for (int i = 0; i < colors; ++i)
{
byte b = bitmap[palette_offset];
byte g = bitmap[palette_offset+1];
byte r = bitmap[palette_offset+2];
alpha_map[i] = (byte)((b + g + r) / 3);
palette_offset += 4;
}
}
else
{
for (int i = 0; i < 0x100; ++i)
alpha_map[i] = (byte)i;
}
int src_pixel_size = info.BPP/8;
int src_stride = (int)info.Width*src_pixel_size;
var pixels = new byte[info.Width * info.Height * 4];
int dst = 0;
for (int y = (int)info.Height-1; y >= 0; --y)
{
int src = src_pixels + y*src_stride;
int alpha = src_alpha + y*(int)info.Width;
for (uint x = 0; x < info.Width; ++x)
{
pixels[dst++] = bitmap[src];
pixels[dst++] = bitmap[src+1];
pixels[dst++] = bitmap[src+2];
pixels[dst++] = (byte)~alpha_map[bitmap[alpha++]];
src += src_pixel_size;
}
}
return ImageData.Create (info, PixelFormats.Bgra32, null, pixels);
}
static byte[] ConvertCM (byte[] input, int width, int height, int bpp)
{
int src = LittleEndian.ToInt32 (input, 0x0a);
int pixel_size = bpp / 8;
var bitmap = new byte[input.Length];
Buffer.BlockCopy (input, 0, bitmap, 0, src);
int stride = width * pixel_size;
int i = src;
for (int p = 0; p < pixel_size; ++p)
{
for (int y = 0; y < height; ++y)
{
int pixel = y * stride + p;
for (int x = 0; x < width; ++x)
{
bitmap[src+pixel] = input[i++];
pixel += pixel_size;
}
}
}
return bitmap;
}
}
internal class RleReader : IDataUnpacker, IDisposable
{
BinaryReader m_input;
byte[] m_output;
int m_size;
public byte[] Data { get { return m_output; } }
public RleReader (Stream input, int input_length, int output_length)
{
m_input = new ArcView.Reader (input);
m_output = new byte[output_length];
m_size = input_length;
}
public void UnpackV2 ()
{
int src = 0;
int dst = 0;
while (dst < m_output.Length && src < m_size)
{
byte b = m_input.ReadByte();
int count = m_input.ReadByte();
src += 2;
count = Math.Min (count, m_output.Length - dst);
for (int i = 0; i < count; i++)
m_output[dst++] = b;
}
}
public void Unpack ()
{
int src = 0;
int dst = 0;
while (dst < m_output.Length && src < m_size)
{
byte ctl = m_input.ReadByte();
++src;
if (0 == ctl)
{
int count = m_input.ReadByte();
++src;
count = Math.Min (count, m_output.Length - dst);
int read = m_input.Read (m_output, dst, count);
dst += count;
src += count;
}
else
{
int count = ctl;
byte b = m_input.ReadByte();
++src;
count = Math.Min (count, m_output.Length - dst);
for (int i = 0; i < count; i++)
m_output[dst++] = b;
}
}
}
#region IDisposable Members
bool disposed = false;
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!disposed)
{
if (disposing)
{
m_input.Dispose();
}
disposed = true;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
using System.Runtime.Remoting.Lifetime;
using System.Runtime.Remoting;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class serves as a surrogate for the build engine. It limits access to the build engine by implementing only a subset
/// of all public methods on the Engine class.
/// </summary>
internal sealed class EngineProxy : MarshalByRefObject, IBuildEngine3
{
#region Data
// The logging interface
private EngineLoggingServices loggingServices;
// We've already computed and cached the line/column number of the task node in the project file.
private bool haveProjectFileLocation = false;
// The line number of the task node in the calling project file.
private int lineNumber;
// The column number of the task node in the calling project file.
private int columnNumber;
/// <summary>
/// The full path to the project that's currently building.
/// </summary>
private string parentProjectFullFileName;
/// <summary>
/// The project file that contains the XML for task. This may be an import file and not the primary
/// project file
/// </summary>
private string projectFileOfTaskNode;
/// <summary>
/// The token identifing the context of this evaluation
/// </summary>
private int handleId;
/// <summary>
/// Continue on error value per batch exposed via IBuildEngine
/// </summary>
private bool continueOnError;
/// <summary>
/// The module within which this class has been created. Used for all callbacks to
/// engine.
/// </summary>
private TaskExecutionModule parentModule;
/// <summary>
/// Event contextual information, this tells the loggers where the task events were fired from
/// </summary>
private BuildEventContext buildEventContext;
/// <summary>
/// True if the task connected to this proxy is alive
/// </summary>
private bool activeProxy;
/// <summary>
/// This reference type is used to block access to a single entry methods of the interface
/// </summary>
private object callbackMonitor;
/// <summary>
/// A client sponsor is a class
/// which will respond to a lease renewal request and will
/// increase the lease time allowing the object to stay in memory
/// </summary>
private ClientSponsor sponsor;
/// <summary>
/// Will hold cached copy of typeof(BuildErrorEventArgs) used by each call to LogError
/// </summary>
private static Type buildErrorEventArgsType = null;
/// <summary>
/// Will hold cached copy of typeof(BuildErrorEventArgs) used by each call to LogError
/// </summary>
private static Type buildWarningEventArgsType = null;
#endregion
/// <summary>
/// Private default constructor disallows parameterless instantiation.
/// </summary>
private EngineProxy()
{
// do nothing
}
/// <summary>
/// Create an instance of this class to represent the IBuildEngine2 interface to the task
/// including the event location where the log messages are raised
/// </summary>
/// <param name="parentModule">Parent Task Execution Module</param>
/// <param name="handleId"></param>
/// <param name="parentProjectFullFileName">the full path to the currently building project</param>
/// <param name="projectFileOfTaskNode">the path to the actual file (project or targets) where the task invocation is located</param>
/// <param name="loggingServices"></param>
/// <param name="buildEventContext">Event Context where events will be seen to be raised from. Task messages will get this as their event context</param>
internal EngineProxy
(
TaskExecutionModule parentModule,
int handleId,
string parentProjectFullFileName,
string projectFileOfTaskNode,
EngineLoggingServices loggingServices,
BuildEventContext buildEventContext
)
{
ErrorUtilities.VerifyThrow(parentModule != null, "No parent module.");
ErrorUtilities.VerifyThrow(loggingServices != null, "No logging services.");
ErrorUtilities.VerifyThrow(projectFileOfTaskNode != null, "Need project file path string");
this.parentModule = parentModule;
this.handleId = handleId;
this.parentProjectFullFileName = parentProjectFullFileName;
this.projectFileOfTaskNode = projectFileOfTaskNode;
this.loggingServices = loggingServices;
this.buildEventContext = buildEventContext;
this.callbackMonitor = new object();
activeProxy = true;
}
/// <summary>
/// Stub implementation -- forwards to engine being proxied.
/// </summary>
public void LogErrorEvent(BuildErrorEventArgs e)
{
ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e));
ErrorUtilities.VerifyThrowInvalidOperation(activeProxy, "AttemptingToLogFromInactiveTask");
if (parentModule.IsRunningMultipleNodes && !e.GetType().IsSerializable)
{
loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name);
return;
}
string message = GetUpdatedMessage(e.File, e.Message, parentProjectFullFileName);
if (ContinueOnError)
{
// Convert the error into a warning. We do this because the whole point of
// ContinueOnError is that a project author expects that the task might fail,
// but wants to ignore the failures. This implies that we shouldn't be logging
// errors either, because you should never have a successful build with errors.
BuildWarningEventArgs warningEvent = new BuildWarningEventArgs
( e.Subcategory,
e.Code,
e.File,
e.LineNumber,
e.ColumnNumber,
e.EndLineNumber,
e.EndColumnNumber,
message, // this is the new message from above
e.HelpKeyword,
e.SenderName);
warningEvent.BuildEventContext = buildEventContext;
loggingServices.LogWarningEvent(warningEvent);
// Log a message explaining why we converted the previous error into a warning.
loggingServices.LogComment(buildEventContext,MessageImportance.Normal, "ErrorConvertedIntoWarning");
}
else
{
if(e.GetType().Equals(BuildErrorEventArgsType))
{
// We'd like to add the project file to the subcategory, but since this property
// is read-only on the BuildErrorEventArgs type, this requires creating a new
// instance. However, if some task logged a custom error type, we don't want to
// impolitely (as we already do above on ContinueOnError) throw the custom type
// data away.
e = new BuildErrorEventArgs
(
e.Subcategory,
e.Code,
e.File,
e.LineNumber,
e.ColumnNumber,
e.EndLineNumber,
e.EndColumnNumber,
message, // this is the new message from above
e.HelpKeyword,
e.SenderName
);
}
e.BuildEventContext = buildEventContext;
loggingServices.LogErrorEvent(e);
}
}
/// <summary>
/// Stub implementation -- forwards to engine being proxied.
/// </summary>
public void LogWarningEvent(BuildWarningEventArgs e)
{
ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e));
ErrorUtilities.VerifyThrowInvalidOperation(activeProxy, "AttemptingToLogFromInactiveTask");
if (parentModule.IsRunningMultipleNodes && !e.GetType().IsSerializable)
{
loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name);
return;
}
if (e.GetType().Equals(BuildWarningEventArgsType))
{
// We'd like to add the project file to the message, but since this property
// is read-only on the BuildWarningEventArgs type, this requires creating a new
// instance. However, if some task logged a custom warning type, we don't want
// to impolitely throw the custom type data away.
string message = GetUpdatedMessage(e.File, e.Message, parentProjectFullFileName);
e = new BuildWarningEventArgs
(
e.Subcategory,
e.Code,
e.File,
e.LineNumber,
e.ColumnNumber,
e.EndLineNumber,
e.EndColumnNumber,
message, // this is the new message from above
e.HelpKeyword,
e.SenderName
);
}
e.BuildEventContext = buildEventContext;
loggingServices.LogWarningEvent(e);
}
/// <summary>
///
/// </summary>
/// <param name="file">File field from the original BuildEventArgs</param>
/// <param name="message">Message field from the original BuildEventArgs</param>
/// <param name="parentProjectFullFileName">Full file name of the parent (building) project.</param>
/// <returns></returns>
private static string GetUpdatedMessage(string file, string message, string parentProjectFullFileName)
{
#if BUILDING_DF_LKG
// In the dogfood LKG, add the project path to the end, because we need it to help diagnose builds.
// Don't bother doing anything if we don't have a project path (e.g., we loaded from XML directly)
if (String.IsNullOrEmpty(parentProjectFullFileName))
{
return message;
}
// Don't bother adding the project file path if it's already in the file part
if(String.Equals(file, parentProjectFullFileName, StringComparison.OrdinalIgnoreCase))
{
return message;
}
string updatedMessage = String.IsNullOrEmpty(message) ?
String.Format(CultureInfo.InvariantCulture, "[{0}]", parentProjectFullFileName) :
String.Format(CultureInfo.InvariantCulture, "{0} [{1}]", message, parentProjectFullFileName);
return updatedMessage;
#else
// In the regular product, don't modify the message. We want to do this properly, with a field on the event args, in a future version.
return message;
#endif
}
/// <summary>
/// Stub implementation -- forwards to engine being proxied.
/// </summary>
public void LogMessageEvent(BuildMessageEventArgs e)
{
ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e));
ErrorUtilities.VerifyThrowInvalidOperation(activeProxy, "AttemptingToLogFromInactiveTask");
if (parentModule.IsRunningMultipleNodes && !e.GetType().IsSerializable)
{
loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name);
return;
}
e.BuildEventContext = buildEventContext;
loggingServices.LogMessageEvent(e);
}
/// <summary>
/// Stub implementation -- forwards to engine being proxied.
/// </summary>
public void LogCustomEvent(CustomBuildEventArgs e)
{
ErrorUtilities.VerifyThrowArgumentNull(e, nameof(e));
ErrorUtilities.VerifyThrowInvalidOperation(activeProxy, "AttemptingToLogFromInactiveTask");
if (parentModule.IsRunningMultipleNodes && !e.GetType().IsSerializable)
{
loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name);
return;
}
e.BuildEventContext = buildEventContext;
loggingServices.LogCustomEvent(e);
}
/// <summary>
/// Returns true if the ContinueOnError flag was set to true for this particular task
/// in the project file.
/// </summary>
public bool ContinueOnError
{
get
{
ErrorUtilities.VerifyThrowInvalidOperation(activeProxy, "AttemptingToLogFromInactiveTask");
return this.continueOnError;
}
}
/// <summary>
/// Called by the task engine to update the value for each batch
/// </summary>
/// <param name="shouldContinueOnError"></param>
internal void UpdateContinueOnError(bool shouldContinueOnError)
{
this.continueOnError = shouldContinueOnError;
}
/// <summary>
/// Retrieves the line number of the task node withing the project file that called it.
/// </summary>
/// <remarks>This method is expensive in terms of perf. Do not call it in mainline scenarios.</remarks>
/// <owner>RGoel</owner>
public int LineNumberOfTaskNode
{
get
{
ErrorUtilities.VerifyThrowInvalidOperation(activeProxy, "AttemptingToLogFromInactiveTask");
ComputeProjectFileLocationOfTaskNode();
return this.lineNumber;
}
}
/// <summary>
/// Retrieves the line number of the task node withing the project file that called it.
/// </summary>
/// <remarks>This method is expensive in terms of perf. Do not call it in mainline scenarios.</remarks>
/// <owner>RGoel</owner>
public int ColumnNumberOfTaskNode
{
get
{
ErrorUtilities.VerifyThrowInvalidOperation(activeProxy, "AttemptingToLogFromInactiveTask");
ComputeProjectFileLocationOfTaskNode();
return this.columnNumber;
}
}
/// <summary>
/// Returns the full path to the project file that contained the call to this task.
/// </summary>
public string ProjectFileOfTaskNode
{
get
{
ErrorUtilities.VerifyThrowInvalidOperation(activeProxy, "AttemptingToLogFromInactiveTask");
return projectFileOfTaskNode;
}
}
/// <summary>
/// Computes the line/column number of the task node in the project file (or .TARGETS file)
/// that called it.
/// </summary>
private void ComputeProjectFileLocationOfTaskNode()
{
if (!haveProjectFileLocation)
{
parentModule.GetLineColumnOfXmlNode(handleId, out this.lineNumber, out this.columnNumber);
haveProjectFileLocation = true;
}
}
/// <summary>
/// Stub implementation -- forwards to engine being proxied.
/// </summary>
/// <param name="projectFileName"></param>
/// <param name="targetNames"></param>
/// <param name="globalProperties"></param>
/// <param name="targetOutputs"></param>
/// <returns>result of call to engine</returns>
public bool BuildProjectFile
(
string projectFileName,
string[] targetNames,
IDictionary globalProperties,
IDictionary targetOutputs
)
{
return BuildProjectFile(projectFileName, targetNames, globalProperties, targetOutputs, null);
}
/// <summary>
/// Stub implementation -- forwards to engine being proxied.
/// </summary>
/// <param name="projectFileName"></param>
/// <param name="targetNames"></param>
/// <param name="globalProperties"></param>
/// <param name="targetOutputs"></param>
/// <param name="toolsVersion">Tools Version to override on the project. May be null</param>
/// <returns>result of call to engine</returns>
public bool BuildProjectFile
(
string projectFileName,
string[] targetNames,
IDictionary globalProperties,
IDictionary targetOutputs,
string toolsVersion
)
{
lock (callbackMonitor)
{
ErrorUtilities.VerifyThrowInvalidOperation(activeProxy, "AttemptingToLogFromInactiveTask");
// Wrap the project name into an array
string[] projectFileNames = new string[1];
projectFileNames[0] = projectFileName;
string[] toolsVersions = new string[1];
toolsVersions[0] = toolsVersion;
IDictionary[] targetOutputsPerProject = new IDictionary[1];
targetOutputsPerProject[0] = targetOutputs;
IDictionary[] globalPropertiesPerProject = new IDictionary[1];
globalPropertiesPerProject[0] = globalProperties;
return parentModule.BuildProjectFile(handleId, projectFileNames, targetNames, globalPropertiesPerProject, targetOutputsPerProject,
loggingServices, toolsVersions, false, false, buildEventContext);
}
}
/// <summary>
/// Stub implementation -- forwards to engine being proxied.
/// </summary>
/// <param name="projectFileNames"></param>
/// <param name="targetNames"></param>
/// <param name="globalProperties"></param>
/// <param name="targetOutputsPerProject"></param>
/// <param name="toolsVersions">Tools Version to overrides per project. May contain null values</param>
/// <param name="unloadProjectsOnCompletion"></param>
/// <returns>result of call to engine</returns>
public bool BuildProjectFilesInParallel
(
string[] projectFileNames,
string[] targetNames,
IDictionary[] globalProperties,
IDictionary[] targetOutputsPerProject,
string[] toolsVersions,
bool useResultsCache,
bool unloadProjectsOnCompletion
)
{
lock (callbackMonitor)
{
return parentModule.BuildProjectFile(handleId, projectFileNames, targetNames, globalProperties,
targetOutputsPerProject, loggingServices,
toolsVersions, useResultsCache, unloadProjectsOnCompletion, buildEventContext);
}
}
/// <summary>
/// Not implemented for the proxy
/// </summary>
public void Yield()
{
}
/// <summary>
/// Not implemented for the proxy
/// </summary>
public void Reacquire()
{
}
/// <summary>
/// Stub implementation -- forwards to engine being proxied.
/// </summary>
/// <remarks>
/// 1) it is acceptable to pass null for both <c>targetNames</c> and <c>targetOutputs</c>
/// 2) if no targets are specified, the default targets are built
///
/// </remarks>
/// <param name="projectFileNames">The project to build.</param>
/// <param name="targetNames">The targets in the project to build (can be null).</param>
/// <param name="globalProperties">An array of hashtables of additional global properties to apply
/// to the child project (array entries can be null).
/// The key and value in the hashtable should both be strings.</param>
/// <param name="removeGlobalProperties">A list of global properties which should be removed.</param>
/// <param name="toolsVersions">A tools version recognized by the Engine that will be used during this build (can be null).</param>
/// <param name="returnTargetOutputs">Should the target outputs be returned in the BuildEngineResults</param>
/// <returns>Returns a structure containing the success or failures of the build and the target outputs by project.</returns>
public BuildEngineResult BuildProjectFilesInParallel
(
string[] projectFileNames,
string[] targetNames,
IDictionary [] globalProperties,
IList<string>[] removeGlobalProperties,
string[] toolsVersions,
bool returnTargetOutputs
)
{
lock (callbackMonitor)
{
ErrorUtilities.VerifyThrowInvalidOperation(activeProxy, "AttemptingToLogFromInactiveTask");
ErrorUtilities.VerifyThrowArgumentNull(projectFileNames, nameof(projectFileNames));
ErrorUtilities.VerifyThrowArgumentNull(globalProperties, "globalPropertiesPerProject");
Dictionary<string, ITaskItem[]>[] targetOutputsPerProject = null;
if (returnTargetOutputs)
{
targetOutputsPerProject = new Dictionary<string, ITaskItem[]>[projectFileNames.Length];
for (int i = 0; i < targetOutputsPerProject.Length; i++)
{
targetOutputsPerProject[i] = new Dictionary<string, ITaskItem[]>(StringComparer.OrdinalIgnoreCase);
}
}
bool result = parentModule.BuildProjectFile(handleId, projectFileNames, targetNames, globalProperties,
targetOutputsPerProject, loggingServices,
toolsVersions, false, false, buildEventContext);
return new BuildEngineResult(result, new List<IDictionary<string, ITaskItem[]>>(targetOutputsPerProject));
}
}
/// <summary>
/// InitializeLifetimeService is called when the remote object is activated.
/// This method will determine how long the lifetime for the object will be.
/// </summary>
public override object InitializeLifetimeService()
{
// Each MarshalByRef object has a reference to the service which
// controls how long the remote object will stay around
ILease lease = (ILease)base.InitializeLifetimeService();
// Set how long a lease should be initially. Once a lease expires
// the remote object will be disconnected and it will be marked as being availiable
// for garbage collection
int initialLeaseTime = 1;
string initialLeaseTimeFromEnvironment = Environment.GetEnvironmentVariable("MSBUILDENGINEPROXYINITIALLEASETIME");
if (!String.IsNullOrEmpty(initialLeaseTimeFromEnvironment))
{
int leaseTimeFromEnvironment;
if (int.TryParse(initialLeaseTimeFromEnvironment , out leaseTimeFromEnvironment) && leaseTimeFromEnvironment > 0)
{
initialLeaseTime = leaseTimeFromEnvironment;
}
}
lease.InitialLeaseTime = TimeSpan.FromMinutes(initialLeaseTime);
// Make a new client sponsor. A client sponsor is a class
// which will respond to a lease renewal request and will
// increase the lease time allowing the object to stay in memory
sponsor = new ClientSponsor();
// When a new lease is requested lets make it last 1 minutes longer.
int leaseExtensionTime = 1;
string leaseExtensionTimeFromEnvironment = Environment.GetEnvironmentVariable("MSBUILDENGINEPROXYLEASEEXTENSIONTIME");
if (!String.IsNullOrEmpty(leaseExtensionTimeFromEnvironment))
{
int leaseExtensionFromEnvironment;
if (int.TryParse(leaseExtensionTimeFromEnvironment , out leaseExtensionFromEnvironment) && leaseExtensionFromEnvironment > 0)
{
leaseExtensionTime = leaseExtensionFromEnvironment;
}
}
sponsor.RenewalTime = TimeSpan.FromMinutes(leaseExtensionTime);
// Register the sponsor which will increase lease timeouts when the lease expires
lease.Register(sponsor);
return lease;
}
/// <summary>
/// Indicates to the EngineProxy that it is no longer needed.
/// Called by TaskEngine when the task using the EngineProxy is done.
/// </summary>
internal void MarkAsInActive()
{
activeProxy = false;
// Since the task has a pointer to this class it may store it in a static field. Null out
// internal data so the leak of this object doesn't lead to a major memory leak.
loggingServices = null;
parentModule = null;
buildEventContext = null;
// Clear out the sponsor (who is responsible for keeping the EngineProxy remoting lease alive until the task is done)
// this will be null if the engineproxy was never sent accross an appdomain boundry.
if (sponsor != null)
{
ILease lease = (ILease)RemotingServices.GetLifetimeService(this);
lease?.Unregister(sponsor);
sponsor.Close();
sponsor = null;
}
}
#region Properties
/// <summary>
/// Provide a way to change the BuildEventContext of the engine proxy. This is important in batching where each batch will need its own buildEventContext.
/// </summary>
internal BuildEventContext BuildEventContext
{
get { return buildEventContext; }
set { buildEventContext = value; }
}
/// <summary>
/// This property allows a task to query whether or not the system is running in single process mode or multi process mode.
/// Single process mode is where the engine is initialized with the number of cpus = 1 and the engine is not a child engine.
/// The engine is in multi process mode when the engine is initialized with a number of cpus > 1 or the engine is a child engine.
/// </summary>
public bool IsRunningMultipleNodes
{
get { return parentModule.IsRunningMultipleNodes; }
}
/// <summary>
/// Cached copy of typeof(BuildErrorEventArgs) used during each call to LogError
/// </summary>
private static Type BuildErrorEventArgsType
{
get
{
if (buildErrorEventArgsType == null)
{
buildErrorEventArgsType = typeof(BuildErrorEventArgs);
}
return buildErrorEventArgsType;
}
}
/// <summary>
/// Cached copy of typeof(BuildWarningEventArgs) used during each call to LogWarning
/// </summary>
private static Type BuildWarningEventArgsType
{
get
{
if (buildWarningEventArgsType == null)
{
buildWarningEventArgsType = typeof(BuildWarningEventArgs);
}
return buildWarningEventArgsType;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using NLog;
using Wox.Infrastructure.Logger;
using Wox.Infrastructure;
namespace Wox.Plugin.Folder
{
internal class ContextMenuLoader : IContextMenu
{
private readonly PluginInitContext _context;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public ContextMenuLoader(PluginInitContext context)
{
_context = context;
}
public List<Result> LoadContextMenus(Result selectedResult)
{
var contextMenus = new List<Result>();
if (selectedResult.ContextData is SearchResult record)
{
if (record.Type == ResultType.File)
{
contextMenus.Add(CreateOpenWithEditorResult(record));
contextMenus.Add(CreateOpenContainingFolderResult(record));
}
var icoPath = (record.Type == ResultType.File) ? Main.FileImagePath : Main.FolderImagePath;
var fileOrFolder = (record.Type == ResultType.File) ? "file" : "folder";
contextMenus.Add(new Result
{
Title = "Copy path",
SubTitle = $"Copy the current {fileOrFolder} path to clipboard",
Action = (context) =>
{
try
{
Clipboard.SetText(record.FullPath);
return true;
}
catch (Exception e)
{
var message = "Fail to set text in clipboard";
LogException(message, e);
_context.API.ShowMsg(message);
return false;
}
},
IcoPath = Main.CopyImagePath
});
contextMenus.Add(new Result
{
Title = $"Copy {fileOrFolder}",
SubTitle = $"Copy the {fileOrFolder} to clipboard",
Action = (context) =>
{
try
{
Clipboard.SetFileDropList(new System.Collections.Specialized.StringCollection { record.FullPath });
return true;
}
catch (Exception e)
{
var message = $"Fail to set {fileOrFolder} in clipboard";
LogException(message, e);
_context.API.ShowMsg(message);
return false;
}
},
IcoPath = icoPath
});
if (record.Type == ResultType.File || record.Type == ResultType.Folder)
contextMenus.Add(new Result
{
Title = $"Delete {fileOrFolder}",
SubTitle = $"Delete the selected {fileOrFolder}",
Action = (context) =>
{
try
{
if (record.Type == ResultType.File)
File.Delete(record.FullPath);
else
Directory.Delete(record.FullPath);
}
catch(Exception e)
{
var message = $"Fail to delete {fileOrFolder} at {record.FullPath}";
LogException(message, e);
_context.API.ShowMsg(message);
return false;
}
return true;
},
IcoPath = Main.DeleteFileFolderImagePath
});
if (record.Type == ResultType.File && CanRunAsDifferentUser(record.FullPath))
contextMenus.Add(new Result
{
Title = "Run as different user",
Action = (context) =>
{
try
{
Task.Run(()=> ShellCommand.RunAsDifferentUser(record.FullPath.SetProcessStartInfo()));
}
catch (FileNotFoundException e)
{
var name = "Plugin: Folder";
var message = $"File not found: {e.Message}";
_context.API.ShowMsg(name, message);
}
return true;
},
IcoPath = "Images/app.png"
});
}
return contextMenus;
}
private Result CreateOpenContainingFolderResult(SearchResult record)
{
return new Result
{
Title = "Open containing folder",
Action = _ =>
{
try
{
Process.Start("explorer.exe", $" /select,\"{record.FullPath}\"");
}
catch(Exception e)
{
var message = $"Fail to open file at {record.FullPath}";
LogException(message, e);
_context.API.ShowMsg(message);
return false;
}
return true;
},
IcoPath = Main.FolderImagePath
};
}
private Result CreateOpenWithEditorResult(SearchResult record)
{
string editorPath = "notepad.exe"; // TODO add the ability to create a custom editor
var name = "Open With Editor: " + Path.GetFileNameWithoutExtension(editorPath);
return new Result
{
Title = name,
Action = _ =>
{
try
{
Process.Start(editorPath, record.FullPath);
return true;
}
catch (Exception e)
{
var message = $"Fail to editor for file at {record.FullPath}";
LogException(message, e);
_context.API.ShowMsg(message);
return false;
}
},
IcoPath = editorPath
};
}
public void LogException(string message, Exception e)
{
Logger.WoxError($"{message}", e);
}
private bool CanRunAsDifferentUser(string path)
{
switch(Path.GetExtension(path))
{
case ".exe":
case ".bat":
case ".msi":
return true;
default:
return false;
}
}
}
public class SearchResult
{
public string FullPath { get; set; }
public ResultType Type { get; set; }
}
public enum ResultType
{
Volume,
Folder,
File
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using gView.Framework.Data;
using gView.Framework.Geometry;
using System.Data.Common;
namespace gView.Framework.OGC.DB
{
public class OgcSpatialFeatureclass : IFeatureClass
{
protected string _name, _shapefield, _idfield;
protected geometryType _geomType;
protected bool _hasZ = false;
protected OgcSpatialDataset _dataset;
protected IEnvelope _envelope;
protected Fields _fields = new Fields();
protected ISpatialReference _sRef = null;
internal string _geometry_columns_type = String.Empty;
protected OgcSpatialFeatureclass() { }
public OgcSpatialFeatureclass(OgcSpatialDataset dataset, DataRow geometry_columns_row)
{
_dataset = dataset;
if (_dataset == null || geometry_columns_row == null)
return;
try
{
_lastException = null;
string schema = String.Empty;
try
{
if (!String.IsNullOrEmpty(_dataset.OgcDictionary("geometry_columns.f_table_schema")))
schema = geometry_columns_row[_dataset.OgcDictionary("geometry_columns.f_table_schema")].ToString();
if (!String.IsNullOrEmpty(schema))
schema += ".";
}
catch { schema = ""; }
_name = schema + geometry_columns_row[_dataset.OgcDictionary("geometry_columns.f_table_name")].ToString();
_shapefield = geometry_columns_row[_dataset.OgcDictionary("geometry_columns.f_geometry_column")].ToString();
_idfield = _dataset.OgcDictionary("gid");
// Read Primary Key -> PostGIS id is not always "gid";
string pKey = GetPKey();
if (!String.IsNullOrWhiteSpace(pKey) && !pKey.Equals(_idfield))
_idfield = pKey;
_geometry_columns_type = geometry_columns_row[_dataset.OgcDictionary("geometry_columns.type")].ToString().ToUpper();
switch (_geometry_columns_type)
{
case "MULTIPOLYGON":
case "POLYGON":
case "MULTIPOLYGONM":
case "POLYGONM":
_geomType = geometryType.Polygon;
break;
case "MULTILINESTRING":
case "LINESTRING":
case "MULTILINESTRINGM":
case "LINESTRINGM":
_geomType = geometryType.Polyline;
break;
case "POINT":
case "POINTM":
case "MULTIPOINT":
case "MULTIPOINTM":
_geomType = geometryType.Point;
break;
default:
_geomType = geometryType.Unknown;
break;
}
_hasZ = (int)geometry_columns_row[_dataset.OgcDictionary("geometry_columns.coord_dimension")] == 3;
try
{
int srid = int.Parse(geometry_columns_row[_dataset.OgcDictionary("geometry_columns.srid")].ToString());
if (srid > 0)
{
_sRef = gView.Framework.Geometry.SpatialReference.FromID("epsg:" + srid.ToString());
}
else
{
_sRef = TrySelectSpatialReference(dataset, this);
}
}
catch { }
ReadSchema();
}
catch (Exception ex)
{
_lastException = ex;
string msg = ex.Message;
}
}
private Exception _lastException = null;
protected void ReadSchema()
{
if (_dataset == null) return;
try
{
// Fields
using (DbConnection connection = _dataset.ProviderFactory.CreateConnection())
{
connection.ConnectionString = _dataset.ConnectionString;
connection.Open();
DbCommand command = _dataset.ProviderFactory.CreateCommand();
command.CommandText = _dataset.SelectReadSchema(this.Name); // "select * from " + this.Name;
command.Connection = connection;
//NpgsqlCommand command = new NpgsqlCommand("select * from " + this.Name, connection);
using (DbDataReader schemareader = command.ExecuteReader(CommandBehavior.SchemaOnly))
{
DataTable schema = schemareader.GetSchemaTable();
bool foundId = false, foundShape = false;
foreach (DataRow row in schema.Rows)
{
if (row["ColumnName"].ToString() == _idfield && foundId == false)
{
foundId = true;
_fields.Add(new Field(_idfield, FieldType.ID,
Convert.ToInt32(row["ColumnSize"]),
Convert.ToInt32(row["NumericPrecision"])));
continue;
}
else if (row["ColumnName"].ToString() == _shapefield && foundShape == false)
{
foundShape = true;
_fields.Add(new Field(_shapefield, FieldType.Shape));
continue;
}
if (schema.Columns["IsIdentity"] != null && row["IsIdentity"] != null && (bool)row["IsIdentity"] == true)
{
if (foundId == false)
_idfield = row["ColumnName"].ToString();
foundId = true;
_fields.Add(new Field(_idfield, FieldType.ID,
Convert.ToInt32(row["ColumnSize"]),
Convert.ToInt32(row["NumericPrecision"])));
continue;
}
Field field = new Field(row["ColumnName"].ToString());
if (row["DataType"] == typeof(System.Int32))
field.type = FieldType.integer;
else if (row["DataType"] == typeof(System.Int16))
field.type = FieldType.smallinteger;
else if (row["DataType"] == typeof(System.Int64))
field.type = FieldType.biginteger;
else if (row["DataType"] == typeof(System.DateTime))
field.type = FieldType.Date;
else if (row["DataType"] == typeof(System.Double))
field.type = FieldType.Double;
else if (row["DataType"] == typeof(System.Decimal))
field.type = FieldType.Float;
else if (row["DataType"] == typeof(System.Boolean))
field.type = FieldType.boolean;
else if (row["DataType"] == typeof(System.Char))
field.type = FieldType.character;
else if (row["DataType"] == typeof(System.String))
field.type = FieldType.String;
else if (row["DataType"].ToString() == "Microsoft.SqlServer.Types.SqlGeometry" ||
row["DataType"].ToString() == "Microsoft.SqlServer.Types.SqlGeography")
{
if (foundShape == false)
_shapefield = row["ColumnName"].ToString();
foundShape = true;
field.type = FieldType.String;
}
field.size = Convert.ToInt32(row["ColumnSize"]);
int precision;
if (int.TryParse(row["NumericPrecision"]?.ToString(), out precision))
field.precision = precision;
_fields.Add(field);
}
if (foundId == false)
{
_idfield = String.Empty;
}
}
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
public string GeometryTypeString
{
get { return _geometry_columns_type; }
}
private string GetPKey()
{
string pKeySelect = _dataset.IntegerPrimaryKeyField(_name);
try
{
if (!String.IsNullOrWhiteSpace(pKeySelect))
{
using (DbConnection connection = _dataset.ProviderFactory.CreateConnection())
{
connection.ConnectionString = _dataset.ConnectionString; ;
connection.Open();
DbCommand command = _dataset.ProviderFactory.CreateCommand();
command.CommandText = pKeySelect;
command.Connection = connection;
return command.ExecuteScalar()?.ToString();
}
}
}
catch { }
return String.Empty;
}
#region IFeatureClass Member
public string ShapeFieldName
{
get { return _shapefield; }
}
public gView.Framework.Geometry.IEnvelope Envelope
{
get
{
if (_envelope == null)
{
_envelope = _dataset.FeatureClassEnvelope(this);
}
return _envelope;
}
}
public int CountFeatures
{
get
{
try
{
_lastException = null;
using (DbConnection connection = _dataset.ProviderFactory.CreateConnection())
{
connection.ConnectionString = _dataset.ConnectionString;
connection.Open();
DbCommand command = _dataset.ProviderFactory.CreateCommand();
command.CommandText = "select count(" + _idfield + ") from " + this.Name;
command.Connection = connection;
//NpgsqlCommand command = new NpgsqlCommand("SELECT count(" + _idfield + ") from " + this.Name, connection);
return Convert.ToInt32(command.ExecuteScalar());
}
}
catch (Exception ex)
{
_lastException = ex;
return 0;
}
}
}
public IFeatureCursor GetFeatures(IQueryFilter filter)
{
_lastException = null;
if (filter is IBufferQueryFilter)
{
ISpatialFilter sFilter = BufferQueryFilter.ConvertToSpatialFilter(filter as IBufferQueryFilter);
if (sFilter == null) return null;
return GetFeatures(sFilter);
}
return new OgcSpatialFeatureCursor(this, filter);
}
#endregion
#region ITableClass Member
public ICursor Search(IQueryFilter filter)
{
_lastException = null;
return GetFeatures(filter);
}
public ISelectionSet Select(IQueryFilter filter)
{
filter.SubFields = this.IDFieldName;
if (filter is ISpatialFilter)
filter.AddField(this.ShapeFieldName);
using (IFeatureCursor cursor = (IFeatureCursor)new OgcSpatialFeatureCursor(this, filter))
{
IFeature feat;
SpatialIndexedIDSelectionSet selSet = new SpatialIndexedIDSelectionSet(this.Envelope);
while ((feat = cursor.NextFeature) != null)
{
selSet.AddID(feat.OID, feat.Shape);
}
return selSet;
}
}
public IFields Fields
{
get
{
//List<IField> fields = new List<IField>();
//foreach (IField field in _fields)
//{
// fields.Add(field);
//}
//return fields;
return _fields;
}
}
public IField FindField(string name)
{
foreach (IField field in _fields.ToEnumerable())
{
if (field.name == name) return field;
}
return null;
}
public string IDFieldName
{
get { return _idfield; }
}
#endregion
#region IClass Member
public string Name
{
get { return _name; }
}
public string Aliasname
{
get { return _name; }
}
public IDataset Dataset
{
get { return _dataset; }
}
#endregion
#region IGeometryDef Member
public bool HasZ
{
get { return _hasZ; }
}
public bool HasM
{
get { return false; }
}
virtual public gView.Framework.Geometry.ISpatialReference SpatialReference
{
get { return _sRef; }
}
public gView.Framework.Geometry.geometryType GeometryType
{
get { return _geomType; }
}
public GeometryFieldType GeometryFieldType
{
get
{
return GeometryFieldType.Default;
}
}
#endregion
#region IDebugging
public Exception LastException
{
get { return _lastException; }
set { _lastException = value; }
}
#endregion
public static ISpatialReference TrySelectSpatialReference(OgcSpatialDataset dataset, OgcSpatialFeatureclass fc)
{
try
{
DbCommand sridCommand = dataset.SelectSpatialReferenceIds(fc);
if (sridCommand != null)
{
using (DbConnection connection = dataset.ProviderFactory.CreateConnection())
{
connection.ConnectionString = dataset.ConnectionString;
sridCommand.Connection = connection;
connection.Open();
using (DbDataReader reader = sridCommand.ExecuteReader())
{
while (reader.Read())
{
object sridObj = reader["srid"];
if (sridObj != null && sridObj != DBNull.Value)
{
int srid = Convert.ToInt32(sridObj);
if (srid > 0)
{
var sRef = gView.Framework.Geometry.SpatialReference.FromID("epsg:" + srid.ToString());
if (sRef != null)
return sRef;
}
}
}
}
connection.Close();
}
}
}
catch(Exception ex)
{
string msg = ex.Message;
}
return null;
}
}
}
| |
'From Squeak3.7alpha of 11 September 2003 [latest update: #5764] on 4 March 2004 at 3:17:53 pm'!
"Change Set: q11-kbdNav-sw
Date: 3 March 2004
Author: Scott Wallace
Merges Squeakland updates 0169kbdProjectNav-sw and the (presumed) 0194modularCmdKeys-sw.
Integrated with Squeak 3.7a/5764 (there were collisions with babel work).
Allows a thread to be navigated from the keyboard, using:
NEXT: space right-arrow down-arrow.
PREV: backspace, left-arrow, up-arrow
FIRST: Home
LAST: End
Menu items are added to the main ThreadNavigatorMorph's menu to associate the thread with keystroke handling.
Once set up, the keyboard handling remains in place as you navigate from project to project.
Makes the handling of desktop command keys modular. Users can modify the handling of desktop command keys in a non-invasive way, and individual projects can define their own custom handling for desktop command keys."!
!PasteUpMorph methodsFor: 'world menu' stamp: 'sw 3/13/2003 13:52'!
commandKeySelectors
"Answer my command-key table"
| aDict |
aDict _ self valueOfProperty: #commandKeySelectors ifAbsentPut: [self initializeDesktopCommandKeySelectors].
^ aDict! !
!PasteUpMorph methodsFor: 'world menu' stamp: 'sw 2/23/2004 18:33'!
defaultDesktopCommandKeyTriplets
"Answer a list of triplets of the form
<key> <receiver> <selector> [+ optional fourth element, a <description> for use in desktop-command-key-help]
that will provide the default desktop command key handlers. If the selector takes an argument, that argument will be the command-key event"
^ {
{ $b. Browser. #openBrowser. 'Open a new System Browser'}.
{ $k. Workspace. #open. 'Open a new, blank Workspace'}.
{ $m. self. #putUpNewMorphMenu. 'Put up the "New Morph" menu'}.
{ $o. ActiveWorld. #activateObjectsTool. 'Activate the "Objects Tool"'}.
{ $r. ActiveWorld. #restoreMorphicDisplay. 'Redraw the screen'}.
{ $t. self. #findATranscript:. 'Make a System Transcript visible'}.
{ $w. SystemWindow. #closeTopWindow. 'Close the topmost window'}.
{ $z. self. #undoOrRedoCommand. 'Undo or redo the last undoable command'}.
{ $C. self. #findAChangeSorter:. 'Make a Change Sorter visible'}.
{ $F. CurrentProjectRefactoring. #currentToggleFlapsSuppressed. 'Toggle the display of flaps'}.
{ $L. self. #findAFileList:. 'Make a File List visible'}.
{ $N. self. #toggleClassicNavigatorIfAppropriate. 'Show/Hide the classic Navigator, if appropriate'}.
{ $P. self. #findAPreferencesPanel:. 'Activate the Preferences tool'}.
{ $R. self. #openRecentSubmissionsBrowser: . 'Make a Recent Submissions browser visible'}.
{ $W. self. #findAMessageNamesWindow:. 'Make a MessageNames tool visible'}.
{ $Z. ChangeList. #browseRecentLog. 'Browse recently-logged changes'}.
{ $\. SystemWindow. #sendTopWindowToBack. 'Send the top window to the back'}.}! !
!PasteUpMorph methodsFor: 'world menu' stamp: 'sw 3/13/2003 12:19'!
dispatchCommandKeyInWorld: aChar event: evt
"Dispatch the desktop command key if possible. Answer whether handled"
| aMessageSend |
aMessageSend _ self commandKeySelectors at: aChar ifAbsent: [^ false].
aMessageSend selector numArgs = 0
ifTrue:
[aMessageSend value]
ifFalse:
[aMessageSend valueWithArguments: (Array with: evt)].
^ true
! !
!PasteUpMorph methodsFor: 'world menu' stamp: 'sw 3/13/2003 13:52'!
initializeDesktopCommandKeySelectors
"Provide the starting settings for desktop command key selectors. Answer the dictionary."
"ActiveWorld initializeDesktopCommandKeySelectors"
| dict messageSend |
dict _ IdentityDictionary new.
self defaultDesktopCommandKeyTriplets do:
[:trip |
messageSend _ MessageSend receiver: trip second selector: trip third.
dict at: trip first put: messageSend].
self setProperty: #commandKeySelectors toValue: dict.
^ dict
! !
!PasteUpMorph methodsFor: 'world menu' stamp: 'sw 5/20/2003 15:04'!
keyboardNavigationHandler
"Answer the receiver's existing keyboardNavigationHandler, or nil if none."
| aHandler |
aHandler _ self valueOfProperty: #keyboardNavigationHandler ifAbsent: [^ nil].
(aHandler hasProperty: #moribund) ifTrue: "got clobbered in another project"
[self removeProperty: #keyboardNavigationHander.
^ nil].
^ aHandler! !
!PasteUpMorph methodsFor: 'world menu' stamp: 'sw 3/18/2003 23:10'!
keyboardNavigationHandler: aHandler
"Set the receiver's keyboard navigation handler as indicated. A nil argument means to remove the handler"
aHandler
ifNil:
[self removeProperty: #keyboardNavigationHandler]
ifNotNil:
[self setProperty: #keyboardNavigationHandler toValue: aHandler]! !
!PasteUpMorph methodsFor: 'world menu' stamp: 'sw 5/20/2003 14:59'!
keystrokeInWorld: evt
"A keystroke was hit when no keyboard focus was in set, so it is sent here to the world instead."
| aChar isCmd ascii |
aChar _ evt keyCharacter.
(ascii _ aChar asciiValue) = 27 ifTrue: "escape key"
[^ self putUpWorldMenuFromEscapeKey].
(#(1 4 8 28 29 30 31 32) includes: ascii) ifTrue: "home, end, backspace, arrow keys, space"
[self keyboardNavigationHandler ifNotNilDo:
[:aHandler | ^ aHandler navigateFromKeystroke: aChar]].
isCmd _ evt commandKeyPressed and: [Preferences cmdKeysInText].
(evt commandKeyPressed and: [Preferences eToyFriendly])
ifTrue:
[(aChar == $W) ifTrue: [^ self putUpWorldMenu: evt]].
(isCmd and: [Preferences honorDesktopCmdKeys]) ifTrue:
[self dispatchCommandKeyInWorld: aChar event: evt]! !
!PasteUpMorph methodsFor: 'world menu' stamp: 'sw 3/13/2003 11:51'!
putUpNewMorphMenu
"Put up the New Morph menu in the world"
TheWorldMenu new adaptToWorld: self; newMorph! !
!PasteUpMorph methodsFor: 'world menu' stamp: 'sw 3/13/2003 13:56'!
respondToCommand: aCharacter bySending: aSelector to: aReceiver
"Respond to the command-key use of the given character by sending the given selector to the given receiver. If the selector is nil, retract any prior such setting"
aSelector
ifNil:
[self commandKeySelectors removeKey: aCharacter]
ifNotNil:
[self commandKeySelectors at: aCharacter put: (MessageSend receiver: aReceiver selector: aSelector)]! !
!PasteUpMorph methodsFor: 'world menu' stamp: 'sw 3/13/2003 11:58'!
toggleClassicNavigatorIfAppropriate
"If appropriate, toggle the presence of classic navigator"
Preferences classicNavigatorEnabled ifTrue: [^ Preferences togglePreference: #showProjectNavigator]! !
!PasteUpMorph methodsFor: 'world menu' stamp: 'sw 3/13/2003 12:25'!
undoOrRedoCommand
"Undo or redo the last command recorded in the world"
^ self commandHistory undoOrRedoCommand! !
!ThreadNavigationMorph methodsFor: 'navigation' stamp: 'sw 3/19/2003 01:08'!
navigateFromKeystroke: aChar
"A character was typed in an effort to do interproject navigation along the receiver's thread"
| ascii |
ascii _ aChar asciiValue.
(#(29 31 32) includes: ascii) ifTrue: [^ self nextPage]. "right arrow, down arrow, space"
(#(8 28 30) includes: ascii) ifTrue: [^ self previousPage]. "left arrow, up arrow, backspace"
(#(1) includes: ascii) ifTrue: [^ self firstPage].
(#(4) includes: ascii) ifTrue: [^ self lastPage].
self beep.! !
!InternalThreadNavigationMorph methodsFor: 'navigation' stamp: 'sw 3/3/2004 16:58'!
destroyThread
"Manually destroy the thread"
(self confirm: ('Destroy thread <{1}> ?' translated format:{threadName})) ifFalse: [^ self].
self class knownThreads removeKey: threadName ifAbsent: [].
self setProperty: #moribund toValue: true. "In case pointed to in some other project"
ActiveWorld keyboardNavigationHandler == self ifTrue:
[self stopKeyboardNavigation].
self delete! !
!InternalThreadNavigationMorph methodsFor: 'navigation' stamp: 'sw 3/3/2004 17:21'!
moreCommands
"Put up a menu of options"
| allThreads aMenu others target |
allThreads _ self class knownThreads.
aMenu _ MenuMorph new defaultTarget: self.
aMenu addTitle: 'navigation' translated.
aMenu addStayUpItem.
self flag: #deferred. "Probably don't want that stay-up item, not least because the navigation-keystroke stuff is not dynamically handled"
others _ (allThreads keys reject: [ :each | each = threadName]) asSortedCollection.
others do: [ :each |
aMenu add: ('switch to <{1}>' translated format:{each}) selector: #switchToThread: argument: each].
aMenu addList: {
{'switch to recent projects' translated. #getRecentThread}.
#-.
{'create a new thread' translated. #threadOfNoProjects}.
{'edit this thread' translated. #editThisThread}.
{'create thread of all projects' translated. #threadOfAllProjects}.
#-.
{'First project in thread' translated. #firstPage}.
{'Last project in thread' translated. #lastPage}}.
(target _ self currentIndex + 2) > listOfPages size ifFalse:
[aMenu
add: ('skip over next project ({1})' translated format:{(listOfPages at: target - 1) first})
action: #skipOverNext].
aMenu addList: {
{'jump within this thread' translated. #jumpWithinThread}.
{'insert new project' translated. #insertNewProject}.
#-.
{'simply close this navigator' translated. #delete}.
{'destroy this thread' destroyThread}.
#-}.
(ActiveWorld keyboardNavigationHandler == self)
ifFalse:
[aMenu add: 'start keyboard navigation with this thread' translated action: #startKeyboardNavigation]
ifTrue:
[aMenu add: 'stop keyboard navigation with this thread' translated action: #stopKeyboardNavigation].
aMenu popUpInWorld! !
!InternalThreadNavigationMorph methodsFor: 'navigation' stamp: 'sw 3/18/2003 23:12'!
startKeyboardNavigation
"Tell the active world to starting navigating via desktop keyboard navigation via me"
ActiveWorld keyboardNavigationHandler: self! !
!InternalThreadNavigationMorph methodsFor: 'navigation' stamp: 'sw 3/18/2003 23:09'!
stopKeyboardNavigation
"Cease navigating via the receiver in response to desktop keystrokes"
ActiveWorld removeProperty: #keyboardNavigationHandler! !
!InternalThreadNavigationMorph methodsFor: 'private' stamp: 'sw 3/3/2004 17:03'!
loadPageWithProgress
"Load the desired page, showing a progress indicator as we go"
| projectInfo projectName beSpaceHandler |
projectInfo _ listOfPages at: currentIndex.
projectName _ projectInfo first.
loadedProject _ Project named: projectName.
self class know: listOfPages as: threadName.
beSpaceHandler _ (ActiveWorld keyboardNavigationHandler == self).
WorldState addDeferredUIMessage:
[InternalThreadNavigationMorph openThreadNamed: threadName atIndex: currentIndex beKeyboardHandler: beSpaceHandler] fixTemps.
loadedProject ifNil: [
ComplexProgressIndicator new
targetMorph: self;
historyCategory: 'project loading' translated;
withProgressDo: [
[
loadedProject _ CurrentProjectRefactoring
currentFromMyServerLoad: projectName
]
on: ProjectViewOpenNotification
do: [ :ex | ex resume: false]
"we probably don't want a project view morph in this case"
].
].
loadedProject ifNil: [
^self inform: 'I cannot find that project' translated
].
self delete.
loadedProject enter.
! !
!InternalThreadNavigationMorph class methodsFor: 'known threads' stamp: 'sw 3/18/2003 23:12'!
openThreadNamed: nameOfThread atIndex: anInteger beKeyboardHandler: aBoolean
"Activate the thread of the given name, from the given index; set it up to be navigated via desktop keys if indicated"
| coll nav |
coll _ self knownThreads at: nameOfThread ifAbsent: [^self].
nav _ World
submorphThat: [ :each | (each isKindOf: self) and: [each threadName = nameOfThread]]
ifNone:
[nav _ self basicNew.
nav
listOfPages: coll;
threadName: nameOfThread index: anInteger;
initialize;
openInWorld;
positionAppropriately.
aBoolean ifTrue: [ActiveWorld keyboardNavigationHandler: nav].
^ self].
nav
listOfPages: coll;
threadName: nameOfThread index: anInteger;
removeAllMorphs;
addButtons.
aBoolean ifTrue: [ActiveWorld keyboardNavigationHandler: nav]
! !
!InternalThreadNavigationMorph class reorganize!
('thumbnails' cacheThumbnailFor: clearThumbnailCache getThumbnailFor:)
('parts bin' descriptionForPartsBin)
('known threads' know:as: knownThreads openThreadNamed:atIndex: openThreadNamed:atIndex:beKeyboardHandler:)
('sorter' sorterFormForProject:sized:)
!
!InternalThreadNavigationMorph reorganize!
('initialization' addButtons defaultColor ensureSuitableDefaults)
('navigation' buttonForMenu deleteCurrentPage destroyThread editThisThread getRecentThread insertNewProject insertNewProjectActionFor: jumpToIndex: jumpWithinThread moreCommands myThumbnailSize positionAppropriately skipOverNext startKeyboardNavigation stopKeyboardNavigation switchToThread: threadName threadName:index: threadOfAllProjects threadOfNoProjects)
('sorting' acceptSortedContentsFrom: makeThumbnailForPageNumber:scaledToSize:default:)
('menu' showMenuFor:event:)
('stepping' step)
('piano rolls' triggerActionFromPianoRoll)
('private' currentIndex listOfPages: loadPageWithProgress)
('accessing' sizeRatio)
!
!ThreadNavigationMorph reorganize!
('initialization' addButtons colorForButtons defaultColor fontForButtons initialize makeButton:balloonText:for:)
('navigation' deleteCurrentPage ensureSuitableDefaults exitTheSequence firstPage lastPage navigateFromKeystroke: nextPage previousPage)
('stepping' step stepTime wantsSteps)
('buttons' buttonExit buttonFirst buttonForward buttonLast buttonPrevious)
('menu' showMenuFor:event:)
('private' currentIndex listOfPages: loadPage loadPageWithProgress morphicLayerNumber)
!
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.AspNet.Identity
{
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using Adxstudio.Xrm.AspNet.Cms;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Web;
using Microsoft.Owin;
using Xrm.Cms;
public class IdentityError
{
public string Code { get; set; }
public string Description { get; set; }
}
public class IdentityErrorDescriber
{
public IContentMapProvider ContentMapProvider { get; private set; }
public ContextLanguageInfo Language { get; private set; }
public IdentityErrorDescriber(IOwinContext context)
: this(context.GetContentMapProvider(), context.GetContextLanguageInfo())
{
}
public IdentityErrorDescriber(IContentMapProvider contentMapProvider, ContextLanguageInfo language)
{
if (contentMapProvider == null)
{
throw new ArgumentNullException("contentMapProvider");
}
this.ContentMapProvider = contentMapProvider;
this.Language = language;
}
public virtual IdentityError DefaultError()
{
var guid = WebEventSource.Log.GenericErrorException(null);
return GetError(string.Format(ResourceManager.GetString("Generic_Error_Message"), guid));
}
public virtual IdentityError ConcurrencyFailure()
{
return GetError(ResourceManager.GetString("Optimistic_Concurrency_Failure_Exception"));
}
public virtual IdentityError PasswordMismatch()
{
return GetError(ResourceManager.GetString("Incorrect_Password_Exception"));
}
public virtual IdentityError InvalidToken()
{
return GetError(ResourceManager.GetString("Invalid_Token_Exception"));
}
public virtual IdentityError LoginAlreadyAssociated()
{
return GetError(ResourceManager.GetString("User_Already_Exists_Exception"));
}
public virtual IdentityError InvalidUserName(string name)
{
return GetError(ResourceManager.GetString("User_Name_Invalid_Can_Only_Contain_Letters_Digits_Exception"), name);
}
public virtual IdentityError InvalidEmail(string email)
{
return GetError(ResourceManager.GetString("Invalid_Email_Exception"), email);
}
public virtual IdentityError DuplicateUserName(string name)
{
return GetError(ResourceManager.GetString("User_Name_Alredy_Taken_Exception"), name);
}
public virtual IdentityError DuplicateEmail(string email)
{
return GetError(ResourceManager.GetString("Email_Already_Used_Exception"), email);
}
public virtual IdentityError InvalidRoleName(string name)
{
return GetError(ResourceManager.GetString("Invalid_Rolename_Exception"), name);
}
public virtual IdentityError DuplicateRoleName(string name)
{
return GetError(ResourceManager.GetString("Role_Name_Already_Taken_Exception"), name);
}
public virtual IdentityError UserAlreadyHasPassword()
{
return GetError(ResourceManager.GetString("User_Already_Has_Password_Set_Exception"));
}
public virtual IdentityError UserLockoutNotEnabled()
{
return GetError(ResourceManager.GetString("Lockout_Is_Disabled_For_This_User"));
}
public virtual IdentityError UserAlreadyInRole(string role)
{
return GetError(ResourceManager.GetString("User_Alredy_In_Role_Exception"), role);
}
public virtual IdentityError UserNotInRole(string role)
{
return GetError(ResourceManager.GetString("User_Not_In_Role_Exception"), role);
}
public virtual IdentityError PasswordTooShort(int length)
{
return GetError(ResourceManager.GetString("Password_Error_For_Characters"), length);
}
public virtual IdentityError PasswordRequiresNonLetterAndDigit()
{
return GetError(string.Format(ResourceManager.GetString("Password_Errors"), "non letter and non digit character"));
}
public virtual IdentityError PasswordRequiresDigit()
{
return GetError(string.Format(ResourceManager.GetString("Password_Errors"), "digit ('0'-'9')"));
}
public virtual IdentityError PasswordRequiresLower()
{
return GetError(string.Format(ResourceManager.GetString("Password_Errors"), "lowercase ('a'-'z')"));
}
public virtual IdentityError PasswordRequiresUpper()
{
return GetError(string.Format(ResourceManager.GetString("Password_Errors"), "uppercase ('A'-'Z')"));
}
public virtual IdentityError PasswordRequiresThreeClasses()
{
return GetError(ResourceManager.GetString("Passwords_Not_Meeting_Requirement"));
}
protected virtual IdentityError GetError(string message, object arg = null, [CallerMemberName] string code = null)
{
return this.ContentMapProvider.Using(map =>
{
var description = map.GetSnippet("Account/Errors/" + code, this.Language) ?? message;
return new IdentityError
{
Code = code,
Description = string.Format(CultureInfo.CurrentCulture, description, new[] { arg })
};
});
}
}
public class CrmIdentityErrorDescriber : IdentityErrorDescriber
{
public CrmIdentityErrorDescriber(IOwinContext context)
: base(context)
{
}
public virtual IdentityError UserLocked()
{
return GetError(ResourceManager.GetString("User_Account_Locked_Exception"));
}
public virtual IdentityError InvalidLogin()
{
return GetError(ResourceManager.GetString("Authentication_Error_Invalid_Login"));
}
public virtual IdentityError InvalidTwoFactorCode()
{
return GetError(ResourceManager.GetString("Invalid_Code_Exception"));
}
public virtual IdentityError InvalidInvitationCode()
{
return GetError(ResourceManager.GetString("Invalid_Invitation_Code_Exception"));
}
public virtual IdentityError EmailRequired()
{
return GetError(ResourceManager.GetString("Email_Field_Required_Exception"));
}
public virtual IdentityError UserNameRequired()
{
return GetError(ResourceManager.GetString("User_Name_Field_Required_Exception"));
}
public virtual IdentityError PasswordConfirmationFailure()
{
return GetError(ResourceManager.GetString("Registration_Error_Password_Confirmation_Failure"));
}
public virtual IdentityError NewPasswordConfirmationFailure()
{
return GetError(ResourceManager.GetString("Old_New_Password_Should_Not_Match_Exception"));
}
internal IdentityError InvalidUserNameWithComma(string name)
{
return GetError(ResourceManager.GetString("User_Name_Invalid_Exception"), name);
}
public virtual IdentityError TooManyAttempts()
{
return GetError(ResourceManager.GetString("Authentication_Error_TooMany_Attempts"));
}
/// <summary>
/// Returns a localized message for invalid email.
/// </summary>
/// <returns>localized message as string</returns>
public virtual IdentityError ValidEmailRequired()
{
return GetError(ResourceManager.GetString("Invalid_Email_Message"));
}
/// <summary>
/// Localized message for required password
/// </summary>
/// <returns>Localized message as string</returns>
public virtual IdentityError PasswordRequired()
{
return GetError(ResourceManager.GetString("Password_Is_Required_Field_Error"));
}
/// <summary>
/// Using the existing pattern for captcha message.
/// </summary>
/// <param name="message"></param>
/// <returns>Error message</returns>
public virtual IdentityError CaptchaRequired(string message)
{
return GetError(message);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;
namespace LibGit2Sharp
{
/// <summary>
/// Holds the meta data of a <see cref="Tree"/>.
/// </summary>
public class TreeDefinition
{
private readonly Dictionary<string, TreeEntryDefinition> entries = new Dictionary<string, TreeEntryDefinition>();
private readonly Dictionary<string, TreeDefinition> unwrappedTrees = new Dictionary<string, TreeDefinition>();
/// <summary>
/// Builds a <see cref="TreeDefinition"/> from an existing <see cref="Tree"/>.
/// </summary>
/// <param name="tree">The <see cref="Tree"/> to be processed.</param>
/// <returns>A new <see cref="TreeDefinition"/> holding the meta data of the <paramref name="tree"/>.</returns>
public static TreeDefinition From(Tree tree)
{
Ensure.ArgumentNotNull(tree, "tree");
var td = new TreeDefinition();
foreach (TreeEntry treeEntry in tree)
{
td.Add(treeEntry.Name, treeEntry);
}
return td;
}
/// <summary>
/// Builds a <see cref="TreeDefinition"/> from a <see cref="Commit"/>'s <see cref="Tree"/>.
/// </summary>
/// <param name="commit">The <see cref="Commit"/> whose tree is to be processed</param>
/// <returns>A new <see cref="TreeDefinition"/> holding the meta data of the <paramref name="commit"/>'s <see cref="Tree"/>.</returns>
public static TreeDefinition From(Commit commit)
{
Ensure.ArgumentNotNull(commit, "commit");
return From(commit.Tree);
}
private void AddEntry(string targetTreeEntryName, TreeEntryDefinition treeEntryDefinition)
{
if (entries.ContainsKey(targetTreeEntryName))
{
WrapTree(targetTreeEntryName, treeEntryDefinition);
return;
}
entries.Add(targetTreeEntryName, treeEntryDefinition);
}
/// <summary>
/// Removes a <see cref="TreeEntryDefinition"/> located the specified <paramref name="treeEntryPath"/> path.
/// </summary>
/// <param name="treeEntryPath">The path within this <see cref="TreeDefinition"/>.</param>
/// <returns>The current <see cref="TreeDefinition"/>.</returns>
public virtual TreeDefinition Remove(string treeEntryPath)
{
Ensure.ArgumentNotNullOrEmptyString(treeEntryPath, "treeEntryPath");
if (this[treeEntryPath] == null)
{
return this;
}
Tuple<string, string> segments = ExtractPosixLeadingSegment(treeEntryPath);
if (segments.Item2 == null)
{
entries.Remove(segments.Item1);
}
if (!unwrappedTrees.ContainsKey(segments.Item1))
{
return this;
}
if (segments.Item2 != null)
{
unwrappedTrees[segments.Item1].Remove(segments.Item2);
}
if (unwrappedTrees[segments.Item1].entries.Count == 0)
{
unwrappedTrees.Remove(segments.Item1);
entries.Remove(segments.Item1);
}
return this;
}
/// <summary>
/// Adds or replaces a <see cref="TreeEntryDefinition"/> at the specified <paramref name="targetTreeEntryPath"/> location.
/// </summary>
/// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param>
/// <param name="treeEntryDefinition">The <see cref="TreeEntryDefinition"/> to be stored at the described location.</param>
/// <returns>The current <see cref="TreeDefinition"/>.</returns>
public virtual TreeDefinition Add(string targetTreeEntryPath, TreeEntryDefinition treeEntryDefinition)
{
Ensure.ArgumentNotNullOrEmptyString(targetTreeEntryPath, "targetTreeEntryPath");
Ensure.ArgumentNotNull(treeEntryDefinition, "treeEntryDefinition");
if (Path.IsPathRooted(targetTreeEntryPath))
{
throw new ArgumentException("The provided path is an absolute path.");
}
if (treeEntryDefinition is TransientTreeTreeEntryDefinition)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"The {0} references a target which hasn't been created in the {1} yet. " +
"This situation can occur when the target is a whole new {2} being created, or when an existing {2} is being updated because some of its children were added/removed.",
typeof(TreeEntryDefinition).Name, typeof(ObjectDatabase).Name, typeof(Tree).Name));
}
Tuple<string, string> segments = ExtractPosixLeadingSegment(targetTreeEntryPath);
if (segments.Item2 != null)
{
TreeDefinition td = RetrieveOrBuildTreeDefinition(segments.Item1, true);
td.Add(segments.Item2, treeEntryDefinition);
}
else
{
AddEntry(segments.Item1, treeEntryDefinition);
}
return this;
}
/// <summary>
/// Adds or replaces a <see cref="TreeEntryDefinition"/>, built from the provided <see cref="TreeEntry"/>, at the specified <paramref name="targetTreeEntryPath"/> location.
/// </summary>
/// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param>
/// <param name="treeEntry">The <see cref="TreeEntry"/> to be stored at the described location.</param>
/// <returns>The current <see cref="TreeDefinition"/>.</returns>
public virtual TreeDefinition Add(string targetTreeEntryPath, TreeEntry treeEntry)
{
Ensure.ArgumentNotNull(treeEntry, "treeEntry");
TreeEntryDefinition ted = TreeEntryDefinition.From(treeEntry);
return Add(targetTreeEntryPath, ted);
}
/// <summary>
/// Adds or replaces a <see cref="TreeEntryDefinition"/>, dynamically built from the provided <see cref="Blob"/>, at the specified <paramref name="targetTreeEntryPath"/> location.
/// </summary>
/// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param>
/// <param name="blob">The <see cref="Blob"/> to be stored at the described location.</param>
/// <param name="mode">The file related <see cref="Mode"/> attributes.</param>
/// <returns>The current <see cref="TreeDefinition"/>.</returns>
public virtual TreeDefinition Add(string targetTreeEntryPath, Blob blob, Mode mode)
{
Ensure.ArgumentNotNull(blob, "blob");
Ensure.ArgumentConformsTo(mode, m => m.HasAny(TreeEntryDefinition.BlobModes), "mode");
TreeEntryDefinition ted = TreeEntryDefinition.From(blob, mode);
return Add(targetTreeEntryPath, ted);
}
/// <summary>
/// Adds or replaces a <see cref="TreeEntryDefinition"/>, dynamically built from the content of the file, at the specified <paramref name="targetTreeEntryPath"/> location.
/// </summary>
/// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param>
/// <param name="filePath">The path to the file from which a <see cref="Blob"/> will be built and stored at the described location. A relative path is allowed to be passed if the target
/// <see cref="Repository"/> is a standard, non-bare, repository. The path will then be considered as a path relative to the root of the working directory.</param>
/// <param name="mode">The file related <see cref="Mode"/> attributes.</param>
/// <returns>The current <see cref="TreeDefinition"/>.</returns>
public virtual TreeDefinition Add(string targetTreeEntryPath, string filePath, Mode mode)
{
Ensure.ArgumentNotNullOrEmptyString(filePath, "filePath");
TreeEntryDefinition ted = TreeEntryDefinition.TransientBlobFrom(filePath, mode);
return Add(targetTreeEntryPath, ted);
}
/// <summary>
/// Adds or replaces a <see cref="TreeEntryDefinition"/>, dynamically built from the provided <see cref="Tree"/>, at the specified <paramref name="targetTreeEntryPath"/> location.
/// </summary>
/// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param>
/// <param name="tree">The <see cref="Tree"/> to be stored at the described location.</param>
/// <returns>The current <see cref="TreeDefinition"/>.</returns>
public virtual TreeDefinition Add(string targetTreeEntryPath, Tree tree)
{
Ensure.ArgumentNotNull(tree, "tree");
TreeEntryDefinition ted = TreeEntryDefinition.From(tree);
return Add(targetTreeEntryPath, ted);
}
/// <summary>
/// Adds or replaces a gitlink <see cref="TreeEntryDefinition"/> equivalent to <paramref name="submodule"/>.
/// </summary>
/// <param name="submodule">The <see cref="Submodule"/> to be linked.</param>
/// <returns>The current <see cref="TreeDefinition"/>.</returns>
public virtual TreeDefinition Add(Submodule submodule)
{
Ensure.ArgumentNotNull(submodule, "submodule");
return AddGitLink(submodule.Path, submodule.HeadCommitId);
}
/// <summary>
/// Adds or replaces a gitlink <see cref="TreeEntryDefinition"/>,
/// referencing the commit identified by <paramref name="objectId"/>,
/// at the specified <paramref name="targetTreeEntryPath"/> location.
/// </summary>
/// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param>
/// <param name="objectId">The <see cref="ObjectId"/> of the commit to be linked at the described location.</param>
/// <returns>The current <see cref="TreeDefinition"/>.</returns>
public virtual TreeDefinition AddGitLink(string targetTreeEntryPath, ObjectId objectId)
{
Ensure.ArgumentNotNull(objectId, "objectId");
var ted = TreeEntryDefinition.From(objectId);
return Add(targetTreeEntryPath, ted);
}
private TreeDefinition RetrieveOrBuildTreeDefinition(string treeName, bool shouldOverWrite)
{
TreeDefinition td;
if (unwrappedTrees.TryGetValue(treeName, out td))
{
return td;
}
TreeEntryDefinition treeEntryDefinition;
bool hasAnEntryBeenFound = entries.TryGetValue(treeName, out treeEntryDefinition);
if (hasAnEntryBeenFound)
{
switch (treeEntryDefinition.TargetType)
{
case TreeEntryTargetType.Tree:
td = From(treeEntryDefinition.Target as Tree);
break;
case TreeEntryTargetType.Blob:
case TreeEntryTargetType.GitLink:
if (shouldOverWrite)
{
td = new TreeDefinition();
break;
}
return null;
default:
throw new NotImplementedException();
}
}
else
{
if (!shouldOverWrite)
{
return null;
}
td = new TreeDefinition();
}
entries[treeName] = new TransientTreeTreeEntryDefinition();
unwrappedTrees.Add(treeName, td);
return td;
}
internal Tree Build(Repository repository)
{
WrapAllTreeDefinitions(repository);
using (var builder = new TreeBuilder(repository))
{
var builtTreeEntryDefinitions = new List<Tuple<string, TreeEntryDefinition>>(entries.Count);
foreach (KeyValuePair<string, TreeEntryDefinition> kvp in entries)
{
string name = kvp.Key;
TreeEntryDefinition ted = kvp.Value;
var transient = ted as TransientBlobTreeEntryDefinition;
if (transient == null)
{
builder.Insert(name, ted);
continue;
}
Blob blob = transient.Builder(repository.ObjectDatabase);
TreeEntryDefinition ted2 = TreeEntryDefinition.From(blob, ted.Mode);
builtTreeEntryDefinitions.Add(new Tuple<string, TreeEntryDefinition>(name, ted2));
builder.Insert(name, ted2);
}
builtTreeEntryDefinitions.ForEach(t => entries[t.Item1] = t.Item2);
ObjectId treeId = builder.Write();
return repository.Lookup<Tree>(treeId);
}
}
private void WrapAllTreeDefinitions(Repository repository)
{
foreach (KeyValuePair<string, TreeDefinition> pair in unwrappedTrees)
{
Tree tree = pair.Value.Build(repository);
entries[pair.Key] = TreeEntryDefinition.From(tree);
}
unwrappedTrees.Clear();
}
private void WrapTree(string entryName, TreeEntryDefinition treeEntryDefinition)
{
entries[entryName] = treeEntryDefinition;
unwrappedTrees.Remove(entryName);
}
/// <summary>
/// Retrieves the <see cref="TreeEntryDefinition"/> located the specified <paramref name="treeEntryPath"/> path.
/// </summary>
/// <param name="treeEntryPath">The path within this <see cref="TreeDefinition"/>.</param>
/// <returns>The found <see cref="TreeEntryDefinition"/> if any; null otherwise.</returns>
public virtual TreeEntryDefinition this[string treeEntryPath]
{
get
{
Ensure.ArgumentNotNullOrEmptyString(treeEntryPath, "treeEntryPath");
Tuple<string, string> segments = ExtractPosixLeadingSegment(treeEntryPath);
if (segments.Item2 != null)
{
TreeDefinition td = RetrieveOrBuildTreeDefinition(segments.Item1, false);
return td == null ? null : td[segments.Item2];
}
TreeEntryDefinition treeEntryDefinition;
return !entries.TryGetValue(segments.Item1, out treeEntryDefinition) ? null : treeEntryDefinition;
}
}
private static Tuple<string, string> ExtractPosixLeadingSegment(FilePath targetPath)
{
string[] segments = targetPath.Posix.Split(new[] { '/' }, 2);
if (segments[0] == string.Empty || (segments.Length == 2 && (segments[1] == string.Empty || segments[1].StartsWith("/", StringComparison.Ordinal))))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid path.", targetPath));
}
return new Tuple<string, string>(segments[0], segments.Length == 2 ? segments[1] : null);
}
private class TreeBuilder : IDisposable
{
private readonly TreeBuilderSafeHandle handle;
public TreeBuilder(Repository repo)
{
handle = Proxy.git_treebuilder_new(repo.Handle);
}
public void Insert(string name, TreeEntryDefinition treeEntryDefinition)
{
Proxy.git_treebuilder_insert(handle, name, treeEntryDefinition);
}
public ObjectId Write()
{
return Proxy.git_treebuilder_write(handle);
}
public void Dispose()
{
handle.SafeDispose();
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: File
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: A collection of methods for manipulating Files.
**
** April 09,2000 (some design refactorization)
**
===========================================================*/
using System;
using System.Security.Permissions;
using PermissionSet = System.Security.PermissionSet;
using Win32Native = Microsoft.Win32.Win32Native;
using System.Runtime.InteropServices;
using System.Security;
#if FEATURE_MACL
using System.Security.AccessControl;
#endif
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System.IO {
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
[ComVisible(true)]
public static class File
{
private const int GetFileExInfoStandard = 0;
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static StreamReader OpenText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return new StreamReader(path);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
public static StreamWriter CreateText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return new StreamWriter(path,false);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static StreamWriter AppendText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return new StreamWriter(path,true);
}
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName and Create
// and Write permissions to destFileName.
//
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Copy(String sourceFileName, String destFileName) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, false, true);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName
// and Write permissions to destFileName.
//
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Copy(String sourceFileName, String destFileName, bool overwrite) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, overwrite, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeCopy(String sourceFileName, String destFileName, bool overwrite) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, overwrite, false);
}
/// <devdoc>
/// Note: This returns the fully qualified name of the destination file.
/// </devdoc>
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost) {
Contract.Requires(sourceFileName != null);
Contract.Requires(destFileName != null);
Contract.Requires(sourceFileName.Length > 0);
Contract.Requires(destFileName.Length > 0);
String fullSourceFileName = Path.GetFullPathInternal(sourceFileName);
String fullDestFileName = Path.GetFullPathInternal(destFileName);
#if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY
if (checkHost) {
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
sourceState.EnsureState();
destState.EnsureState();
}
#elif !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.Read, new String[] { fullSourceFileName }, false, false ).Demand();
new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullDestFileName }, false, false ).Demand();
#endif
bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite);
if (!r) {
// Save Win32 error because subsequent checks will overwrite this HRESULT.
int errorCode = Marshal.GetLastWin32Error();
String fileName = destFileName;
if (errorCode != Win32Native.ERROR_FILE_EXISTS) {
// For a number of error codes (sharing violation, path
// not found, etc) we don't know if the problem was with
// the source or dest file. Try reading the source file.
using(SafeFileHandle handle = Win32Native.UnsafeCreateFile(fullSourceFileName, FileStream.GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero)) {
if (handle.IsInvalid)
fileName = sourceFileName;
}
if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
if (Directory.InternalExists(fullDestFileName))
throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName);
}
}
__Error.WinIOError(errorCode, fileName);
}
return fullDestFileName;
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite accessand cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream Create(String path) {
return Create(path, FileStream.DefaultBufferSize);
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite access and cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
public static FileStream Create(String path, int bufferSize) {
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream Create(String path, int bufferSize, FileOptions options) {
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite,
FileShare.None, bufferSize, options);
}
#if FEATURE_MACL
public static FileStream Create(String path, int bufferSize, FileOptions options, FileSecurity fileSecurity) {
return new FileStream(path, FileMode.Create, FileSystemRights.Read | FileSystemRights.Write,
FileShare.None, bufferSize, options, fileSecurity);
}
#endif
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped.
//
// Your application must have Delete permission to the target file.
//
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Delete(String path) {
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly) {
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
InternalDelete(path, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeDelete(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
InternalDelete(path, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void InternalDelete(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, path, fullPath);
state.EnsureState();
}
#elif !FEATURE_CORECLR
// For security check, path should be resolved to an absolute path.
new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullPath }, false, false).Demand();
#endif
bool r = Win32Native.DeleteFile(fullPath);
if (!r) {
int hr = Marshal.GetLastWin32Error();
if (hr==Win32Native.ERROR_FILE_NOT_FOUND)
return;
else
__Error.WinIOError(hr, fullPath);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Decrypt(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
#if FEATURE_PAL
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_RequiresNT"));
#else
String fullPath = Path.GetFullPathInternal(path);
new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, new String[] { fullPath }, false, false).Demand();
bool r = Win32Native.DecryptFile(fullPath, 0);
if (!r) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
// Check to see if the file system is not NTFS. If so,
// throw a different exception.
DriveInfo di = new DriveInfo(Path.GetPathRoot(fullPath));
if (!String.Equals("NTFS", di.DriveFormat))
throw new NotSupportedException(Environment.GetResourceString("NotSupported_EncryptionNeedsNTFS"));
}
__Error.WinIOError(errorCode, fullPath);
}
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Encrypt(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
#if FEATURE_PAL
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_RequiresNT"));
#else
String fullPath = Path.GetFullPathInternal(path);
new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, new String[] { fullPath }, false, false).Demand();
bool r = Win32Native.EncryptFile(fullPath);
if (!r) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
// Check to see if the file system is not NTFS. If so,
// throw a different exception.
DriveInfo di = new DriveInfo(Path.GetPathRoot(fullPath));
if (!String.Equals("NTFS", di.DriveFormat))
throw new NotSupportedException(Environment.GetResourceString("NotSupported_EncryptionNeedsNTFS"));
}
__Error.WinIOError(errorCode, fullPath);
}
#endif
}
// Tests if a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return true.
//
// Your application must have Read permission for the target directory.
//
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static bool Exists(String path)
{
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly) {
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
return InternalExistsHelper(path, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static bool UnsafeExists(String path)
{
return InternalExistsHelper(path, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static bool InternalExistsHelper(String path, bool checkHost)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
path = Path.GetFullPathInternal(path);
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPathInternal should never return null
Contract.Assert(path != null, "File.Exists: GetFullPathInternal returned null");
if (path.Length > 0 && Path.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
}
#if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, path);
state.EnsureState();
}
#elif !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.Read, new String[] { path }, false, false).Demand();
#endif
return InternalExists(path);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
[System.Security.SecurityCritical] // auto-generated
internal static bool InternalExists(String path) {
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(path, ref data, false, true);
return (dataInitialised == 0) && (data.fileAttributes != -1)
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream Open(String path, FileMode mode) {
return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream Open(String path, FileMode mode, FileAccess access) {
return Open(path,mode, access, FileShare.None);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream Open(String path, FileMode mode, FileAccess access, FileShare share) {
return new FileStream(path, mode, access, share);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetCreationTime(String path, DateTime creationTime)
{
SetCreationTimeUtc(path, creationTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public unsafe static void SetCreationTimeUtc(String path, DateTime creationTimeUtc)
{
SafeFileHandle handle;
using(OpenFile(path, FileAccess.Write, out handle)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, &fileTime, null, null);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetCreationTime(String path)
{
return InternalGetCreationTimeUtc(path, true).ToLocalTime();
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetCreationTimeUtc(String path)
{
return InternalGetCreationTimeUtc(path, false); // this API isn't exposed in Silverlight
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static DateTime InternalGetCreationTimeUtc(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
#elif !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.Read, new String[] { fullPath }, false, false ).Demand();
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow);
return DateTime.FromFileTimeUtc(dt);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetLastAccessTime(String path, DateTime lastAccessTime)
{
SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public unsafe static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
{
SafeFileHandle handle;
using(OpenFile(path, FileAccess.Write, out handle)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, null, &fileTime, null);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastAccessTime(String path)
{
return InternalGetLastAccessTimeUtc(path, true).ToLocalTime();
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastAccessTimeUtc(String path)
{
return InternalGetLastAccessTimeUtc(path, false); // this API isn't exposed in Silverlight
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static DateTime InternalGetLastAccessTimeUtc(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
#elif !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.Read, new String[] { fullPath }, false, false ).Demand();
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow);
return DateTime.FromFileTimeUtc(dt);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetLastWriteTime(String path, DateTime lastWriteTime)
{
SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public unsafe static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
{
SafeFileHandle handle;
using(OpenFile(path, FileAccess.Write, out handle)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, null, null, &fileTime);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastWriteTime(String path)
{
return InternalGetLastWriteTimeUtc(path, true).ToLocalTime();
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastWriteTimeUtc(String path)
{
return InternalGetLastWriteTimeUtc(path, false); // this API isn't exposed in Silverlight
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static DateTime InternalGetLastWriteTimeUtc(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
#elif !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.Read, new String[] { fullPath }, false, false ).Demand();
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow);
return DateTime.FromFileTimeUtc(dt);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileAttributes GetAttributes(String path)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
#elif !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.Read, new String[] { fullPath }, false, false).Demand();
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, true);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
return (FileAttributes) data.fileAttributes;
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetAttributes(String path, FileAttributes fileAttributes)
{
String fullPath = Path.GetFullPathInternal(path);
#if !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullPath }, false, false).Demand();
#endif
bool r = Win32Native.SetFileAttributes(fullPath, (int) fileAttributes);
if (!r) {
int hr = Marshal.GetLastWin32Error();
if (hr==ERROR_INVALID_PARAMETER)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileAttrs"));
__Error.WinIOError(hr, fullPath);
}
}
#if FEATURE_MACL
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileSecurity GetAccessControl(String path)
{
return GetAccessControl(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileSecurity GetAccessControl(String path, AccessControlSections includeSections)
{
// Appropriate security check should be done for us by FileSecurity.
return new FileSecurity(path, includeSections);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetAccessControl(String path, FileSecurity fileSecurity)
{
if (fileSecurity == null)
throw new ArgumentNullException("fileSecurity");
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
// Appropriate security check should be done for us by FileSecurity.
fileSecurity.Persist(fullPath);
}
#endif
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#elif FEATURE_LEGACYNETCF
[System.Security.SecuritySafeCritical]
#endif // FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream OpenRead(String path) {
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly) {
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream OpenWrite(String path) {
return new FileStream(path, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String ReadAllText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllText(path, Encoding.UTF8, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String ReadAllText(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllText(path, encoding, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static String UnsafeReadAllText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllText(path, Encoding.UTF8, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static String InternalReadAllText(String path, Encoding encoding, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
using (StreamReader sr = new StreamReader(path, encoding, true, StreamReader.DefaultBufferSize, checkHost))
return sr.ReadToEnd();
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#else //FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecuritySafeCritical] // auto-generated
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, true);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#else //FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecuritySafeCritical] // auto-generated
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllText(path, contents, encoding, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeWriteAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalWriteAllText(String path, String contents, Encoding encoding, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
using (StreamWriter sw = new StreamWriter(path, false, encoding, StreamWriter.DefaultBufferSize, checkHost))
sw.Write(contents);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static byte[] ReadAllBytes(String path)
{
return InternalReadAllBytes(path, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static byte[] UnsafeReadAllBytes(String path)
{
return InternalReadAllBytes(path, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static byte[] InternalReadAllBytes(String path, bool checkHost)
{
byte[] bytes;
using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost)) {
// Do a blocking read
int index = 0;
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
throw new IOException(Environment.GetResourceString("IO.IO_FileTooLong2GB"));
int count = (int) fileLength;
bytes = new byte[count];
while(count > 0) {
int n = fs.Read(bytes, index, count);
if (n == 0)
__Error.EndOfFile();
index += n;
count -= n;
}
}
return bytes;
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllBytes(String path, byte[] bytes)
{
if (path == null)
throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bytes == null)
throw new ArgumentNullException("bytes");
Contract.EndContractBlock();
InternalWriteAllBytes(path, bytes, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeWriteAllBytes(String path, byte[] bytes)
{
if (path == null)
throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bytes == null)
throw new ArgumentNullException("bytes");
Contract.EndContractBlock();
InternalWriteAllBytes(path, bytes, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalWriteAllBytes(String path, byte[] bytes, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(path.Length != 0);
Contract.Requires(bytes != null);
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read,
FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost))
{
fs.Write(bytes, 0, bytes.Length);
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] ReadAllLines(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllLines(path, Encoding.UTF8);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] ReadAllLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllLines(path, encoding);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static String[] InternalReadAllLines(String path, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length != 0);
String line;
List<String> lines = new List<String>();
using (StreamReader sr = new StreamReader(path, encoding))
while ((line = sr.ReadLine()) != null)
lines.Add(line);
return lines.ToArray();
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> ReadLines(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "path");
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, Encoding.UTF8);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> ReadLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "path");
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, encoding);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllLines(String path, String[] contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, StreamWriter.UTF8NoBOM), contents);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllLines(String path, String[] contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, encoding), contents);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, StreamWriter.UTF8NoBOM), contents);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, encoding), contents);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalWriteAllLines(TextWriter writer, IEnumerable<String> contents)
{
Contract.Requires(writer != null);
Contract.Requires(contents != null);
using (writer)
{
foreach (String line in contents)
{
writer.WriteLine(line);
}
}
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void AppendAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalAppendAllText(path, contents, StreamWriter.UTF8NoBOM);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void AppendAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalAppendAllText(path, contents, encoding);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalAppendAllText(String path, String contents, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
using (StreamWriter sw = new StreamWriter(path, true, encoding))
sw.Write(contents);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void AppendAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, true, StreamWriter.UTF8NoBOM), contents);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void AppendAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, true, encoding), contents);
}
// Moves a specified file to a new location and potentially a new file name.
// This method does work across volumes.
//
// The caller must have certain FileIOPermissions. The caller must
// have Read and Write permission to
// sourceFileName and Write
// permissions to destFileName.
//
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Move(String sourceFileName, String destFileName) {
InternalMove(sourceFileName, destFileName, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeMove(String sourceFileName, String destFileName) {
InternalMove(sourceFileName, destFileName, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalMove(String sourceFileName, String destFileName, bool checkHost) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
String fullSourceFileName = Path.GetFullPathInternal(sourceFileName);
String fullDestFileName = Path.GetFullPathInternal(destFileName);
#if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY
if (checkHost) {
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
sourceState.EnsureState();
destState.EnsureState();
}
#elif !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { fullSourceFileName }, false, false).Demand();
new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullDestFileName }, false, false).Demand();
#endif
if (!InternalExists(fullSourceFileName))
__Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName);
if (!Win32Native.MoveFile(fullSourceFileName, fullDestFileName))
{
__Error.WinIOError();
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName)
{
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName");
if (destinationFileName == null)
throw new ArgumentNullException("destinationFileName");
Contract.EndContractBlock();
InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, false);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName");
if (destinationFileName == null)
throw new ArgumentNullException("destinationFileName");
Contract.EndContractBlock();
InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalReplace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
Contract.Requires(sourceFileName != null);
Contract.Requires(destinationFileName != null);
// Write permission to all three files, read permission to source
// and dest.
String fullSrcPath = Path.GetFullPathInternal(sourceFileName);
String fullDestPath = Path.GetFullPathInternal(destinationFileName);
String fullBackupPath = null;
if (destinationBackupFileName != null)
fullBackupPath = Path.GetFullPathInternal(destinationBackupFileName);
#if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, sourceFileName, fullSrcPath);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationFileName, fullDestPath);
FileSecurityState backupState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationBackupFileName, fullBackupPath);
sourceState.EnsureState();
destState.EnsureState();
backupState.EnsureState();
#elif !FEATURE_CORECLR
FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, new String[] { fullSrcPath, fullDestPath});
if (destinationBackupFileName != null)
perm.AddPathList(FileIOPermissionAccess.Write, fullBackupPath);
perm.Demand();
#endif
int flags = Win32Native.REPLACEFILE_WRITE_THROUGH;
if (ignoreMetadataErrors)
flags |= Win32Native.REPLACEFILE_IGNORE_MERGE_ERRORS;
bool r = Win32Native.ReplaceFile(fullDestPath, fullSrcPath, fullBackupPath, flags, IntPtr.Zero, IntPtr.Zero);
if (!r)
__Error.WinIOError();
}
// Returns 0 on success, otherwise a Win32 error code. Note that
// classes should use -1 as the uninitialized state for dataInitialized.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
{
int dataInitialised = 0;
if (tryagain) // someone has a handle to the file open, or other error
{
Win32Native.WIN32_FIND_DATA findData;
findData = new Win32Native.WIN32_FIND_DATA ();
// Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error
String tempPath = path.TrimEnd(new char [] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar});
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
bool error = false;
SafeFindHandle handle = Win32Native.FindFirstFile(tempPath,findData);
try {
if (handle.IsInvalid) {
error = true;
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready
{
if (!returnErrorOnNotFound) {
// Return default value for backward compatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
return dataInitialised;
}
}
finally {
// Close the Win32 handle
try {
handle.Close();
}
catch {
// if we're already returning an error, don't throw another one.
if (!error) {
Contract.Assert(false, "File::FillAttributeInfo - FindClose failed!");
__Error.WinIOError();
}
}
}
}
finally {
Win32Native.SetErrorMode(oldMode);
}
// Copy the information to data
data.PopulateFrom(findData);
}
else
{
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
bool success = false;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data);
}
finally {
Win32Native.SetErrorMode(oldMode);
}
if (!success) {
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised != Win32Native.ERROR_FILE_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_PATH_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_NOT_READY) // floppy device not ready
{
// In case someone latched onto the file. Take the perf hit only for failure
return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound);
}
else {
if (!returnErrorOnNotFound) {
// Return default value for backward compbatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
}
}
return dataInitialised;
}
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static FileStream OpenFile(String path, FileAccess access, out SafeFileHandle handle)
{
FileStream fs = new FileStream(path, FileMode.Open, access, FileShare.ReadWrite, 1);
handle = fs.SafeFileHandle;
if (handle.IsInvalid) {
// Return a meaningful error, using the RELATIVE path to
// the file to avoid returning extra information to the caller.
// NT5 oddity - when trying to open "C:\" as a FileStream,
// we usually get ERROR_PATH_NOT_FOUND from the OS. We should
// probably be consistent w/ every other directory.
int hr = Marshal.GetLastWin32Error();
String FullPath = Path.GetFullPathInternal(path);
if (hr==__Error.ERROR_PATH_NOT_FOUND && FullPath.Equals(Directory.GetDirectoryRoot(FullPath)))
hr = __Error.ERROR_ACCESS_DENIED;
__Error.WinIOError(hr, path);
}
return fs;
}
// Defined in WinError.h
private const int ERROR_INVALID_PARAMETER = 87;
private const int ERROR_ACCESS_DENIED = 0x5;
}
}
| |
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
public static int form = 0; // Which state the player is in
public bool grounded;
bool CamLock = true;
public static bool facingLeft = true, start = false;
public static bool swimming = false, dead = false, ramStatus = false, pickUp = false;
public Vector2 PosStart, PosEnd;
public static Vector2 SpawnPos;
public static float originalDrag, originalGravity;
private static Vector2 startPos;
private static CameraFade cam;
private static LayerMask mask = ~(3 << 10);
// Checkpoint stuff
private static Vector2[] checkpointArray;
private static int lastCheckpoint = 0;
Animator anim;
// Reset the player to his original position
public static void Reset(Rigidbody2D body)
{
dead = true;
originalGravity = body.gravityScale;
body.gravityScale = 0;
body.velocity=Vector3.zero;
cam.StartFade (new Color(0,0,0,1), 1.0f);
}
// Reset the player to his original position
public static void ResetPos(Rigidbody2D body)
{
Vector2 temp;
dead = false;
temp = body.transform.position;
temp.x = -temp.x;
temp.y = -temp.y;
temp.x += checkpointArray[lastCheckpoint].x;
temp.y += checkpointArray[lastCheckpoint].y;
body.transform.Translate(temp);
body.gravityScale = originalGravity;
cam.StartFade (new Color(0,0,0,0), 0.5f);
}
//Gary
public static void PlaceInWorld(Rigidbody2D body, int xPos, int yPos)
{
cam.StartFade (new Color(0,0,0,1), 1f);
SpawnPos.x = xPos;
SpawnPos.y = yPos;
}
public static void FadeToPosition(Rigidbody2D body, int xPos, int yPos)
{
Vector2 temp;
temp = new Vector2 (xPos, yPos);
body.transform.Translate(temp);
body.gravityScale = originalGravity;
cam.StartFade (new Color(0,0,0,0), 1f);
}
public static void fadeInorOut()
{
if (cam.GetTrans () == 1)
{
}
if (cam.GetTrans () == 0)
{
}
}
// Use this for initialization
void Start ()
{
cam = GetComponent<CameraFade> ();
anim = GetComponent<Animator>();
startPos = rigidbody2D.transform.position;
rigidbody2D.drag = 2;
rigidbody2D.mass = 10;
rigidbody2D.gravityScale = 2;
checkpointArray = new Vector2[]
{
new Vector2(180, 7),
new Vector2(-25, 0),
new Vector2(73, -11),
new Vector2(42, 20),
};
}
public bool isCamLocked()
{
return CamLock;
}
// Update is called once per frame
void Update ()
{
if (dead)
{
if (cam.GetTrans () == 1)
ResetPos(rigidbody2D);
}
else
if (cam.GetTrans () == 1)
{
ResetPos(rigidbody2D);
CamLock = false;
}
bool collision = false;
// Update based on which state the player is in
// (Currently only handles movement)
if(!dead)
switch (form)
{
case 0: // Hub
PlayerHub.Move(rigidbody2D, grounded);
break;
case 1: // Land
PlayerLand.Move(rigidbody2D, grounded);
anim.SetBool("isDeer", true);
break;
case 2: // Water
PlayerWater.Move(rigidbody2D, swimming, grounded);
break;
case 3: // Air
PlayerAir.Move(rigidbody2D, grounded);
break;
default: // Default to Hub
PlayerHub.Move(rigidbody2D, grounded);
break;
}
grounded = false;
//Check the collision using raycasting
BoxCollider2D boxCollider = GetComponent<BoxCollider2D>();
PosStart = transform.position;
PosEnd = transform.position;
PosStart.y -= boxCollider.size.y * transform.localScale.y * 0.8f;
PosEnd.y -= boxCollider.size.y * transform.localScale.y * 0.55f;
RaycastHit2D hit = Physics2D.Linecast(PosStart, PosEnd, mask);
Debug.DrawLine (PosStart, PosEnd, Color.red);
if (hit.collider)
{
if (hit.collider.gameObject.layer == 9)
collision = true;
grounded = true;
}
PosStart.x -= boxCollider.size.x * transform.localScale.x * 0.5f;
PosEnd.x -= boxCollider.size.x * transform.localScale.x * 0.5f;
RaycastHit2D hit2 = Physics2D.Linecast(PosStart, PosEnd, mask);
Debug.DrawLine (PosStart, PosEnd, Color.blue);
if (hit2.collider)
{
if (hit2.collider.gameObject.layer == 9)
collision = true;
grounded = true;
}
//Position for the second ray
PosStart.x += boxCollider.size.x * transform.localScale.x;
PosEnd.x += boxCollider.size.x * transform.localScale.x;
RaycastHit2D hit3 = Physics2D.Linecast(PosStart, PosEnd, mask);
Debug.DrawLine (PosStart, PosEnd, Color.green);
if (hit3.collider)
{
if (hit3.collider.gameObject.layer == 9)
collision = true;
grounded = true;
}
if (grounded)
if(hit.collider)
if (hit.collider.gameObject.layer == 4)
grounded = false;
if(collision)
Physics2D.IgnoreLayerCollision(10, 9, false);
else
Physics2D.IgnoreLayerCollision(10, 9, true);
}
void FixedUpdate()
{
//This is going to need cleaned up so so much.
anim.SetFloat("Speed", Mathf.Abs(rigidbody2D.velocity.x));
anim.SetFloat("YSpeed", Mathf.Abs(rigidbody2D.velocity.y));
if(swimming)
anim.SetBool (("Water"), true);
else
anim.SetBool (("Water"), false);
if (grounded)
{
anim.SetBool (("anim_grounded"), true);
} else
anim.SetBool (("anim_grounded"), false);
if (Input.GetButtonDown("Jump"))
{
if(grounded)
anim.SetBool(("Jump"), true);
}
else
anim.SetBool(("Jump"), false);
if (anim.GetBool("isDeer") == true)
{
if (Input.GetButtonDown("Fire1"))
{
//anim.SetBool(("Action"), true);
anim.Play("DeerRam");
ramStatus = true;
}
else
ramStatus = false;
}
if (Input.GetAxisRaw ("Horizontal") > 0 && facingLeft)
Flip ();
else if (Input.GetAxisRaw ("Horizontal") < 0 && !facingLeft)
Flip ();
}
void Flip()
{
facingLeft = !facingLeft;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
// Change form
public static void SetForm(int a)
{
form = a;
}
// Get the current form
public static int GetForm()
{
return form;
}
// Get the current form
public static bool GetRam()
{
return ramStatus;
}
public static void SetSwimming(bool a)
{
swimming = a;
}
public static bool GetSwimming()
{
return swimming;
}
public static bool GetFacingLeft()
{
return facingLeft;
}
public static void SetCheckpoint(int a)
{
lastCheckpoint = a;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.